babylon.max.js 4.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686
  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. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. BABYLON.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. BABYLON.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. BABYLON.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. BABYLON.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. BABYLON.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. BABYLON.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. // Screenshots
  5772. var screenshotCanvas;
  5773. var cloneValue = function (source, destinationObject) {
  5774. if (!source)
  5775. return null;
  5776. if (source instanceof BABYLON.Mesh) {
  5777. return null;
  5778. }
  5779. if (source instanceof BABYLON.SubMesh) {
  5780. return source.clone(destinationObject);
  5781. }
  5782. else if (source.clone) {
  5783. return source.clone();
  5784. }
  5785. return null;
  5786. };
  5787. var Tools = /** @class */ (function () {
  5788. function Tools() {
  5789. }
  5790. /**
  5791. * Interpolates between a and b via alpha
  5792. * @param a The lower value (returned when alpha = 0)
  5793. * @param b The upper value (returned when alpha = 1)
  5794. * @param alpha The interpolation-factor
  5795. * @return The mixed value
  5796. */
  5797. Tools.Mix = function (a, b, alpha) {
  5798. return a * (1 - alpha) + b * alpha;
  5799. };
  5800. Tools.Instantiate = function (className) {
  5801. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5802. return Tools.RegisteredExternalClasses[className];
  5803. }
  5804. var arr = className.split(".");
  5805. var fn = (window || this);
  5806. for (var i = 0, len = arr.length; i < len; i++) {
  5807. fn = fn[arr[i]];
  5808. }
  5809. if (typeof fn !== "function") {
  5810. return null;
  5811. }
  5812. return fn;
  5813. };
  5814. Tools.SetImmediate = function (action) {
  5815. if (window.setImmediate) {
  5816. window.setImmediate(action);
  5817. }
  5818. else {
  5819. setTimeout(action, 1);
  5820. }
  5821. };
  5822. Tools.IsExponentOfTwo = function (value) {
  5823. var count = 1;
  5824. do {
  5825. count *= 2;
  5826. } while (count < value);
  5827. return count === value;
  5828. };
  5829. /**
  5830. * Find the next highest power of two.
  5831. * @param x Number to start search from.
  5832. * @return Next highest power of two.
  5833. */
  5834. Tools.CeilingPOT = function (x) {
  5835. x--;
  5836. x |= x >> 1;
  5837. x |= x >> 2;
  5838. x |= x >> 4;
  5839. x |= x >> 8;
  5840. x |= x >> 16;
  5841. x++;
  5842. return x;
  5843. };
  5844. /**
  5845. * Find the next lowest power of two.
  5846. * @param x Number to start search from.
  5847. * @return Next lowest power of two.
  5848. */
  5849. Tools.FloorPOT = function (x) {
  5850. x = x | (x >> 1);
  5851. x = x | (x >> 2);
  5852. x = x | (x >> 4);
  5853. x = x | (x >> 8);
  5854. x = x | (x >> 16);
  5855. return x - (x >> 1);
  5856. };
  5857. /**
  5858. * Find the nearest power of two.
  5859. * @param x Number to start search from.
  5860. * @return Next nearest power of two.
  5861. */
  5862. Tools.NearestPOT = function (x) {
  5863. var c = Tools.CeilingPOT(x);
  5864. var f = Tools.FloorPOT(x);
  5865. return (c - x) > (x - f) ? f : c;
  5866. };
  5867. Tools.GetExponentOfTwo = function (value, max, mode) {
  5868. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5869. var pot;
  5870. switch (mode) {
  5871. case BABYLON.Engine.SCALEMODE_FLOOR:
  5872. pot = Tools.FloorPOT(value);
  5873. break;
  5874. case BABYLON.Engine.SCALEMODE_NEAREST:
  5875. pot = Tools.NearestPOT(value);
  5876. break;
  5877. case BABYLON.Engine.SCALEMODE_CEILING:
  5878. default:
  5879. pot = Tools.CeilingPOT(value);
  5880. break;
  5881. }
  5882. return Math.min(pot, max);
  5883. };
  5884. Tools.GetFilename = function (path) {
  5885. var index = path.lastIndexOf("/");
  5886. if (index < 0)
  5887. return path;
  5888. return path.substring(index + 1);
  5889. };
  5890. Tools.GetFolderPath = function (uri) {
  5891. var index = uri.lastIndexOf("/");
  5892. if (index < 0)
  5893. return "";
  5894. return uri.substring(0, index + 1);
  5895. };
  5896. Tools.GetDOMTextContent = function (element) {
  5897. var result = "";
  5898. var child = element.firstChild;
  5899. while (child) {
  5900. if (child.nodeType === 3) {
  5901. result += child.textContent;
  5902. }
  5903. child = child.nextSibling;
  5904. }
  5905. return result;
  5906. };
  5907. Tools.ToDegrees = function (angle) {
  5908. return angle * 180 / Math.PI;
  5909. };
  5910. Tools.ToRadians = function (angle) {
  5911. return angle * Math.PI / 180;
  5912. };
  5913. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5914. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5915. var output = "";
  5916. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5917. var i = 0;
  5918. var bytes = new Uint8Array(buffer);
  5919. while (i < bytes.length) {
  5920. chr1 = bytes[i++];
  5921. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5922. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5923. enc1 = chr1 >> 2;
  5924. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5925. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5926. enc4 = chr3 & 63;
  5927. if (isNaN(chr2)) {
  5928. enc3 = enc4 = 64;
  5929. }
  5930. else if (isNaN(chr3)) {
  5931. enc4 = 64;
  5932. }
  5933. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5934. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5935. }
  5936. return "data:image/png;base64," + output;
  5937. };
  5938. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5939. if (bias === void 0) { bias = null; }
  5940. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5941. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5942. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5943. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5944. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5945. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5946. }
  5947. if (bias) {
  5948. minimum.x -= minimum.x * bias.x + bias.y;
  5949. minimum.y -= minimum.y * bias.x + bias.y;
  5950. minimum.z -= minimum.z * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. maximum.z += maximum.z * bias.x + bias.y;
  5954. }
  5955. return {
  5956. minimum: minimum,
  5957. maximum: maximum
  5958. };
  5959. };
  5960. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5961. if (bias === void 0) { bias = null; }
  5962. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5963. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5964. if (!stride) {
  5965. stride = 3;
  5966. }
  5967. for (var index = start; index < start + count; index++) {
  5968. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5969. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5970. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5971. }
  5972. if (bias) {
  5973. minimum.x -= minimum.x * bias.x + bias.y;
  5974. minimum.y -= minimum.y * bias.x + bias.y;
  5975. minimum.z -= minimum.z * bias.x + bias.y;
  5976. maximum.x += maximum.x * bias.x + bias.y;
  5977. maximum.y += maximum.y * bias.x + bias.y;
  5978. maximum.z += maximum.z * bias.x + bias.y;
  5979. }
  5980. return {
  5981. minimum: minimum,
  5982. maximum: maximum
  5983. };
  5984. };
  5985. Tools.Vector2ArrayFeeder = function (array) {
  5986. return function (index) {
  5987. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5988. var length = isFloatArray ? array.length / 2 : array.length;
  5989. if (index >= length) {
  5990. return null;
  5991. }
  5992. if (isFloatArray) {
  5993. var fa = array;
  5994. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5995. }
  5996. var a = array;
  5997. return a[index];
  5998. };
  5999. };
  6000. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6001. if (bias === void 0) { bias = null; }
  6002. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6003. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6004. var i = 0;
  6005. var cur = feeder(i++);
  6006. while (cur) {
  6007. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6008. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6009. cur = feeder(i++);
  6010. }
  6011. if (bias) {
  6012. minimum.x -= minimum.x * bias.x + bias.y;
  6013. minimum.y -= minimum.y * bias.x + bias.y;
  6014. maximum.x += maximum.x * bias.x + bias.y;
  6015. maximum.y += maximum.y * bias.x + bias.y;
  6016. }
  6017. return {
  6018. minimum: minimum,
  6019. maximum: maximum
  6020. };
  6021. };
  6022. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6023. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6024. return null;
  6025. return Array.isArray(obj) ? obj : [obj];
  6026. };
  6027. // Misc.
  6028. Tools.GetPointerPrefix = function () {
  6029. var eventPrefix = "pointer";
  6030. // Check if pointer events are supported
  6031. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6032. eventPrefix = "mouse";
  6033. }
  6034. return eventPrefix;
  6035. };
  6036. /**
  6037. * @param func - the function to be called
  6038. * @param requester - the object that will request the next frame. Falls back to window.
  6039. */
  6040. Tools.QueueNewFrame = function (func, requester) {
  6041. if (!Tools.IsWindowObjectExist()) {
  6042. return setTimeout(func, 16);
  6043. }
  6044. if (!requester) {
  6045. requester = window;
  6046. }
  6047. if (requester.requestAnimationFrame) {
  6048. return requester.requestAnimationFrame(func);
  6049. }
  6050. else if (requester.msRequestAnimationFrame) {
  6051. return requester.msRequestAnimationFrame(func);
  6052. }
  6053. else if (requester.webkitRequestAnimationFrame) {
  6054. return requester.webkitRequestAnimationFrame(func);
  6055. }
  6056. else if (requester.mozRequestAnimationFrame) {
  6057. return requester.mozRequestAnimationFrame(func);
  6058. }
  6059. else if (requester.oRequestAnimationFrame) {
  6060. return requester.oRequestAnimationFrame(func);
  6061. }
  6062. else {
  6063. return window.setTimeout(func, 16);
  6064. }
  6065. };
  6066. Tools.RequestFullscreen = function (element) {
  6067. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6068. if (!requestFunction)
  6069. return;
  6070. requestFunction.call(element);
  6071. };
  6072. Tools.ExitFullscreen = function () {
  6073. if (document.exitFullscreen) {
  6074. document.exitFullscreen();
  6075. }
  6076. else if (document.mozCancelFullScreen) {
  6077. document.mozCancelFullScreen();
  6078. }
  6079. else if (document.webkitCancelFullScreen) {
  6080. document.webkitCancelFullScreen();
  6081. }
  6082. else if (document.msCancelFullScreen) {
  6083. document.msCancelFullScreen();
  6084. }
  6085. };
  6086. Tools.SetCorsBehavior = function (url, img) {
  6087. if (Tools.CorsBehavior) {
  6088. switch (typeof (Tools.CorsBehavior)) {
  6089. case "function":
  6090. var result = Tools.CorsBehavior(url);
  6091. if (result) {
  6092. img.crossOrigin = result;
  6093. }
  6094. break;
  6095. case "string":
  6096. default:
  6097. img.crossOrigin = Tools.CorsBehavior;
  6098. break;
  6099. }
  6100. }
  6101. };
  6102. // External files
  6103. Tools.CleanUrl = function (url) {
  6104. url = url.replace(/#/mg, "%23");
  6105. return url;
  6106. };
  6107. Tools.LoadImage = function (url, onLoad, onError, database) {
  6108. if (url instanceof ArrayBuffer) {
  6109. url = Tools.EncodeArrayBufferTobase64(url);
  6110. }
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var img = new Image();
  6114. if (url.substr(0, 5) !== "data:") {
  6115. Tools.SetCorsBehavior(url, img);
  6116. }
  6117. img.onload = function () {
  6118. onLoad(img);
  6119. };
  6120. img.onerror = function (err) {
  6121. Tools.Error("Error while trying to load image: " + url);
  6122. if (onError) {
  6123. onError("Error while trying to load image: " + url, err);
  6124. }
  6125. };
  6126. var noIndexedDB = function () {
  6127. img.src = url;
  6128. };
  6129. var loadFromIndexedDB = function () {
  6130. if (database) {
  6131. database.loadImageFromDB(url, img);
  6132. }
  6133. };
  6134. //ANY database to do!
  6135. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6136. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6137. }
  6138. else {
  6139. if (url.indexOf("file:") !== -1) {
  6140. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6141. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6142. try {
  6143. var blobURL;
  6144. try {
  6145. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6146. }
  6147. catch (ex) {
  6148. // Chrome doesn't support oneTimeOnly parameter
  6149. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6150. }
  6151. img.src = blobURL;
  6152. }
  6153. catch (e) {
  6154. img.src = "";
  6155. }
  6156. return img;
  6157. }
  6158. }
  6159. noIndexedDB();
  6160. }
  6161. return img;
  6162. };
  6163. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6164. url = Tools.CleanUrl(url);
  6165. url = Tools.PreprocessUrl(url);
  6166. var request = null;
  6167. var noIndexedDB = function () {
  6168. request = new XMLHttpRequest();
  6169. var loadUrl = Tools.BaseUrl + url;
  6170. request.open('GET', loadUrl, true);
  6171. if (useArrayBuffer) {
  6172. request.responseType = "arraybuffer";
  6173. }
  6174. if (progressCallBack) {
  6175. request.onprogress = progressCallBack;
  6176. }
  6177. request.onreadystatechange = function () {
  6178. var req = request;
  6179. // In case of undefined state in some browsers.
  6180. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6181. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6182. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6183. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6184. }
  6185. else {
  6186. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6187. if (onError) {
  6188. onError(req, e);
  6189. }
  6190. else {
  6191. throw e;
  6192. }
  6193. }
  6194. }
  6195. };
  6196. request.send(null);
  6197. };
  6198. var loadFromIndexedDB = function () {
  6199. if (database) {
  6200. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6201. }
  6202. };
  6203. // If file and file input are set
  6204. if (url.indexOf("file:") !== -1) {
  6205. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6206. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6207. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6208. return request;
  6209. }
  6210. }
  6211. // Caching all files
  6212. if (database && database.enableSceneOffline) {
  6213. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6214. }
  6215. else {
  6216. noIndexedDB();
  6217. }
  6218. return request;
  6219. };
  6220. /**
  6221. * Load a script (identified by an url). When the url returns, the
  6222. * content of this file is added into a new script element, attached to the DOM (body element)
  6223. */
  6224. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6225. var head = document.getElementsByTagName('head')[0];
  6226. var script = document.createElement('script');
  6227. script.type = 'text/javascript';
  6228. script.src = scriptUrl;
  6229. script.onload = function () {
  6230. if (onSuccess) {
  6231. onSuccess();
  6232. }
  6233. };
  6234. script.onerror = function (e) {
  6235. if (onError) {
  6236. onError("Unable to load script", e);
  6237. }
  6238. };
  6239. head.appendChild(script);
  6240. };
  6241. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6242. var reader = new FileReader();
  6243. reader.onload = function (e) {
  6244. //target doesn't have result from ts 1.3
  6245. callback(e.target['result']);
  6246. };
  6247. reader.onprogress = progressCallback;
  6248. reader.readAsDataURL(fileToLoad);
  6249. };
  6250. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6251. var reader = new FileReader();
  6252. reader.onerror = function (e) {
  6253. Tools.Log("Error while reading file: " + fileToLoad.name);
  6254. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6255. };
  6256. reader.onload = function (e) {
  6257. //target doesn't have result from ts 1.3
  6258. callback(e.target['result']);
  6259. };
  6260. if (progressCallBack) {
  6261. reader.onprogress = progressCallBack;
  6262. }
  6263. if (!useArrayBuffer) {
  6264. // Asynchronous read
  6265. reader.readAsText(fileToLoad);
  6266. }
  6267. else {
  6268. reader.readAsArrayBuffer(fileToLoad);
  6269. }
  6270. };
  6271. //returns a downloadable url to a file content.
  6272. Tools.FileAsURL = function (content) {
  6273. var fileBlob = new Blob([content]);
  6274. var url = window.URL || window.webkitURL;
  6275. var link = url.createObjectURL(fileBlob);
  6276. return link;
  6277. };
  6278. // Misc.
  6279. Tools.Format = function (value, decimals) {
  6280. if (decimals === void 0) { decimals = 2; }
  6281. return value.toFixed(decimals);
  6282. };
  6283. Tools.CheckExtends = function (v, min, max) {
  6284. if (v.x < min.x)
  6285. min.x = v.x;
  6286. if (v.y < min.y)
  6287. min.y = v.y;
  6288. if (v.z < min.z)
  6289. min.z = v.z;
  6290. if (v.x > max.x)
  6291. max.x = v.x;
  6292. if (v.y > max.y)
  6293. max.y = v.y;
  6294. if (v.z > max.z)
  6295. max.z = v.z;
  6296. };
  6297. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6298. for (var prop in source) {
  6299. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6300. continue;
  6301. }
  6302. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6303. continue;
  6304. }
  6305. var sourceValue = source[prop];
  6306. var typeOfSourceValue = typeof sourceValue;
  6307. if (typeOfSourceValue === "function") {
  6308. continue;
  6309. }
  6310. if (typeOfSourceValue === "object") {
  6311. if (sourceValue instanceof Array) {
  6312. destination[prop] = [];
  6313. if (sourceValue.length > 0) {
  6314. if (typeof sourceValue[0] == "object") {
  6315. for (var index = 0; index < sourceValue.length; index++) {
  6316. var clonedValue = cloneValue(sourceValue[index], destination);
  6317. if (destination[prop].indexOf(clonedValue) === -1) {
  6318. destination[prop].push(clonedValue);
  6319. }
  6320. }
  6321. }
  6322. else {
  6323. destination[prop] = sourceValue.slice(0);
  6324. }
  6325. }
  6326. }
  6327. else {
  6328. destination[prop] = cloneValue(sourceValue, destination);
  6329. }
  6330. }
  6331. else {
  6332. destination[prop] = sourceValue;
  6333. }
  6334. }
  6335. };
  6336. Tools.IsEmpty = function (obj) {
  6337. for (var i in obj) {
  6338. if (obj.hasOwnProperty(i)) {
  6339. return false;
  6340. }
  6341. }
  6342. return true;
  6343. };
  6344. Tools.RegisterTopRootEvents = function (events) {
  6345. for (var index = 0; index < events.length; index++) {
  6346. var event = events[index];
  6347. window.addEventListener(event.name, event.handler, false);
  6348. try {
  6349. if (window.parent) {
  6350. window.parent.addEventListener(event.name, event.handler, false);
  6351. }
  6352. }
  6353. catch (e) {
  6354. // Silently fails...
  6355. }
  6356. }
  6357. };
  6358. Tools.UnregisterTopRootEvents = function (events) {
  6359. for (var index = 0; index < events.length; index++) {
  6360. var event = events[index];
  6361. window.removeEventListener(event.name, event.handler);
  6362. try {
  6363. if (window.parent) {
  6364. window.parent.removeEventListener(event.name, event.handler);
  6365. }
  6366. }
  6367. catch (e) {
  6368. // Silently fails...
  6369. }
  6370. }
  6371. };
  6372. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6373. if (mimeType === void 0) { mimeType = "image/png"; }
  6374. // Read the contents of the framebuffer
  6375. var numberOfChannelsByLine = width * 4;
  6376. var halfHeight = height / 2;
  6377. //Reading datas from WebGL
  6378. var data = engine.readPixels(0, 0, width, height);
  6379. //To flip image on Y axis.
  6380. for (var i = 0; i < halfHeight; i++) {
  6381. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6382. var currentCell = j + i * numberOfChannelsByLine;
  6383. var targetLine = height - i - 1;
  6384. var targetCell = j + targetLine * numberOfChannelsByLine;
  6385. var temp = data[currentCell];
  6386. data[currentCell] = data[targetCell];
  6387. data[targetCell] = temp;
  6388. }
  6389. }
  6390. // Create a 2D canvas to store the result
  6391. if (!screenshotCanvas) {
  6392. screenshotCanvas = document.createElement('canvas');
  6393. }
  6394. screenshotCanvas.width = width;
  6395. screenshotCanvas.height = height;
  6396. var context = screenshotCanvas.getContext('2d');
  6397. if (context) {
  6398. // Copy the pixels to a 2D canvas
  6399. var imageData = context.createImageData(width, height);
  6400. var castData = (imageData.data);
  6401. castData.set(data);
  6402. context.putImageData(imageData, 0, 0);
  6403. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6404. }
  6405. };
  6406. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6407. if (mimeType === void 0) { mimeType = "image/png"; }
  6408. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6409. if (successCallback) {
  6410. successCallback(base64Image);
  6411. }
  6412. else {
  6413. // We need HTMLCanvasElement.toBlob for HD screenshots
  6414. if (!screenshotCanvas.toBlob) {
  6415. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6416. screenshotCanvas.toBlob = function (callback, type, quality) {
  6417. var _this = this;
  6418. setTimeout(function () {
  6419. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6420. for (var i = 0; i < len; i++) {
  6421. arr[i] = binStr.charCodeAt(i);
  6422. }
  6423. callback(new Blob([arr], { type: type || 'image/png' }));
  6424. });
  6425. };
  6426. }
  6427. screenshotCanvas.toBlob(function (blob) {
  6428. var url = URL.createObjectURL(blob);
  6429. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6430. if (("download" in document.createElement("a"))) {
  6431. var a = window.document.createElement("a");
  6432. a.href = url;
  6433. if (fileName) {
  6434. a.setAttribute("download", fileName);
  6435. }
  6436. else {
  6437. var date = new Date();
  6438. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6439. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6440. }
  6441. window.document.body.appendChild(a);
  6442. a.addEventListener("click", function () {
  6443. if (a.parentElement) {
  6444. a.parentElement.removeChild(a);
  6445. }
  6446. });
  6447. a.click();
  6448. }
  6449. else {
  6450. var newWindow = window.open("");
  6451. if (!newWindow)
  6452. return;
  6453. var img = newWindow.document.createElement("img");
  6454. img.onload = function () {
  6455. // no longer need to read the blob so it's revoked
  6456. URL.revokeObjectURL(url);
  6457. };
  6458. img.src = url;
  6459. newWindow.document.body.appendChild(img);
  6460. }
  6461. });
  6462. }
  6463. };
  6464. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6465. if (mimeType === void 0) { mimeType = "image/png"; }
  6466. var width;
  6467. var height;
  6468. // If a precision value is specified
  6469. if (size.precision) {
  6470. width = Math.round(engine.getRenderWidth() * size.precision);
  6471. height = Math.round(width / engine.getAspectRatio(camera));
  6472. }
  6473. else if (size.width && size.height) {
  6474. width = size.width;
  6475. height = size.height;
  6476. }
  6477. else if (size.width && !size.height) {
  6478. width = size.width;
  6479. height = Math.round(width / engine.getAspectRatio(camera));
  6480. }
  6481. else if (size.height && !size.width) {
  6482. height = size.height;
  6483. width = Math.round(height * engine.getAspectRatio(camera));
  6484. }
  6485. else if (!isNaN(size)) {
  6486. height = size;
  6487. width = size;
  6488. }
  6489. else {
  6490. Tools.Error("Invalid 'size' parameter !");
  6491. return;
  6492. }
  6493. if (!screenshotCanvas) {
  6494. screenshotCanvas = document.createElement('canvas');
  6495. }
  6496. screenshotCanvas.width = width;
  6497. screenshotCanvas.height = height;
  6498. var renderContext = screenshotCanvas.getContext("2d");
  6499. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6500. var newWidth = width;
  6501. var newHeight = newWidth / ratio;
  6502. if (newHeight > height) {
  6503. newHeight = height;
  6504. newWidth = newHeight * ratio;
  6505. }
  6506. var offsetX = Math.max(0, width - newWidth) / 2;
  6507. var offsetY = Math.max(0, height - newHeight) / 2;
  6508. var renderingCanvas = engine.getRenderingCanvas();
  6509. if (renderContext && renderingCanvas) {
  6510. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6511. }
  6512. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6513. };
  6514. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6515. if (mimeType === void 0) { mimeType = "image/png"; }
  6516. if (samples === void 0) { samples = 1; }
  6517. if (antialiasing === void 0) { antialiasing = false; }
  6518. var width;
  6519. var height;
  6520. //If a precision value is specified
  6521. if (size.precision) {
  6522. width = Math.round(engine.getRenderWidth() * size.precision);
  6523. height = Math.round(width / engine.getAspectRatio(camera));
  6524. size = { width: width, height: height };
  6525. }
  6526. else if (size.width && size.height) {
  6527. width = size.width;
  6528. height = size.height;
  6529. }
  6530. else if (size.width && !size.height) {
  6531. width = size.width;
  6532. height = Math.round(width / engine.getAspectRatio(camera));
  6533. size = { width: width, height: height };
  6534. }
  6535. else if (size.height && !size.width) {
  6536. height = size.height;
  6537. width = Math.round(height * engine.getAspectRatio(camera));
  6538. size = { width: width, height: height };
  6539. }
  6540. else if (!isNaN(size)) {
  6541. height = size;
  6542. width = size;
  6543. }
  6544. else {
  6545. Tools.Error("Invalid 'size' parameter !");
  6546. return;
  6547. }
  6548. var scene = camera.getScene();
  6549. var previousCamera = null;
  6550. if (scene.activeCamera !== camera) {
  6551. previousCamera = scene.activeCamera;
  6552. scene.activeCamera = camera;
  6553. }
  6554. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6555. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6556. texture.renderList = null;
  6557. texture.samples = samples;
  6558. if (antialiasing) {
  6559. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6560. }
  6561. texture.onAfterRenderObservable.add(function () {
  6562. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6563. });
  6564. scene.incrementRenderId();
  6565. scene.resetCachedMaterial();
  6566. texture.render(true);
  6567. texture.dispose();
  6568. if (previousCamera) {
  6569. scene.activeCamera = previousCamera;
  6570. }
  6571. camera.getProjectionMatrix(true); // Force cache refresh;
  6572. };
  6573. // XHR response validator for local file scenario
  6574. Tools.ValidateXHRData = function (xhr, dataType) {
  6575. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6576. if (dataType === void 0) { dataType = 7; }
  6577. try {
  6578. if (dataType & 1) {
  6579. if (xhr.responseText && xhr.responseText.length > 0) {
  6580. return true;
  6581. }
  6582. else if (dataType === 1) {
  6583. return false;
  6584. }
  6585. }
  6586. if (dataType & 2) {
  6587. // Check header width and height since there is no "TGA" magic number
  6588. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6589. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6590. return true;
  6591. }
  6592. else if (dataType === 2) {
  6593. return false;
  6594. }
  6595. }
  6596. if (dataType & 4) {
  6597. // Check for the "DDS" magic number
  6598. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6599. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6600. return true;
  6601. }
  6602. else {
  6603. return false;
  6604. }
  6605. }
  6606. }
  6607. catch (e) {
  6608. // Global protection
  6609. }
  6610. return false;
  6611. };
  6612. /**
  6613. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6614. * Be aware Math.random() could cause collisions, but:
  6615. * "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"
  6616. */
  6617. Tools.RandomId = function () {
  6618. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6619. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6620. return v.toString(16);
  6621. });
  6622. };
  6623. Object.defineProperty(Tools, "NoneLogLevel", {
  6624. get: function () {
  6625. return Tools._NoneLogLevel;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Object.defineProperty(Tools, "MessageLogLevel", {
  6631. get: function () {
  6632. return Tools._MessageLogLevel;
  6633. },
  6634. enumerable: true,
  6635. configurable: true
  6636. });
  6637. Object.defineProperty(Tools, "WarningLogLevel", {
  6638. get: function () {
  6639. return Tools._WarningLogLevel;
  6640. },
  6641. enumerable: true,
  6642. configurable: true
  6643. });
  6644. Object.defineProperty(Tools, "ErrorLogLevel", {
  6645. get: function () {
  6646. return Tools._ErrorLogLevel;
  6647. },
  6648. enumerable: true,
  6649. configurable: true
  6650. });
  6651. Object.defineProperty(Tools, "AllLogLevel", {
  6652. get: function () {
  6653. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Tools._AddLogEntry = function (entry) {
  6659. Tools._LogCache = entry + Tools._LogCache;
  6660. if (Tools.OnNewCacheEntry) {
  6661. Tools.OnNewCacheEntry(entry);
  6662. }
  6663. };
  6664. Tools._FormatMessage = function (message) {
  6665. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6666. var date = new Date();
  6667. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6668. };
  6669. Tools._LogDisabled = function (message) {
  6670. // nothing to do
  6671. };
  6672. Tools._LogEnabled = function (message) {
  6673. var formattedMessage = Tools._FormatMessage(message);
  6674. console.log("BJS - " + formattedMessage);
  6675. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6676. Tools._AddLogEntry(entry);
  6677. };
  6678. Tools._WarnDisabled = function (message) {
  6679. // nothing to do
  6680. };
  6681. Tools._WarnEnabled = function (message) {
  6682. var formattedMessage = Tools._FormatMessage(message);
  6683. console.warn("BJS - " + formattedMessage);
  6684. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6685. Tools._AddLogEntry(entry);
  6686. };
  6687. Tools._ErrorDisabled = function (message) {
  6688. // nothing to do
  6689. };
  6690. Tools._ErrorEnabled = function (message) {
  6691. Tools.errorsCount++;
  6692. var formattedMessage = Tools._FormatMessage(message);
  6693. console.error("BJS - " + formattedMessage);
  6694. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6695. Tools._AddLogEntry(entry);
  6696. };
  6697. Object.defineProperty(Tools, "LogCache", {
  6698. get: function () {
  6699. return Tools._LogCache;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Tools.ClearLogCache = function () {
  6705. Tools._LogCache = "";
  6706. Tools.errorsCount = 0;
  6707. };
  6708. Object.defineProperty(Tools, "LogLevels", {
  6709. set: function (level) {
  6710. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6711. Tools.Log = Tools._LogEnabled;
  6712. }
  6713. else {
  6714. Tools.Log = Tools._LogDisabled;
  6715. }
  6716. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6717. Tools.Warn = Tools._WarnEnabled;
  6718. }
  6719. else {
  6720. Tools.Warn = Tools._WarnDisabled;
  6721. }
  6722. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6723. Tools.Error = Tools._ErrorEnabled;
  6724. }
  6725. else {
  6726. Tools.Error = Tools._ErrorDisabled;
  6727. }
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Tools.IsWindowObjectExist = function () {
  6733. return (typeof window) !== "undefined";
  6734. };
  6735. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6736. get: function () {
  6737. return Tools._PerformanceNoneLogLevel;
  6738. },
  6739. enumerable: true,
  6740. configurable: true
  6741. });
  6742. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6743. get: function () {
  6744. return Tools._PerformanceUserMarkLogLevel;
  6745. },
  6746. enumerable: true,
  6747. configurable: true
  6748. });
  6749. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6750. get: function () {
  6751. return Tools._PerformanceConsoleLogLevel;
  6752. },
  6753. enumerable: true,
  6754. configurable: true
  6755. });
  6756. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6757. set: function (level) {
  6758. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6759. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6760. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6761. return;
  6762. }
  6763. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6764. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6765. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6766. return;
  6767. }
  6768. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6769. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6775. };
  6776. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6777. };
  6778. Tools._StartUserMark = function (counterName, condition) {
  6779. if (condition === void 0) { condition = true; }
  6780. if (!Tools._performance) {
  6781. if (!Tools.IsWindowObjectExist()) {
  6782. return;
  6783. }
  6784. Tools._performance = window.performance;
  6785. }
  6786. if (!condition || !Tools._performance.mark) {
  6787. return;
  6788. }
  6789. Tools._performance.mark(counterName + "-Begin");
  6790. };
  6791. Tools._EndUserMark = function (counterName, condition) {
  6792. if (condition === void 0) { condition = true; }
  6793. if (!condition || !Tools._performance.mark) {
  6794. return;
  6795. }
  6796. Tools._performance.mark(counterName + "-End");
  6797. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6798. };
  6799. Tools._StartPerformanceConsole = function (counterName, condition) {
  6800. if (condition === void 0) { condition = true; }
  6801. if (!condition) {
  6802. return;
  6803. }
  6804. Tools._StartUserMark(counterName, condition);
  6805. if (console.time) {
  6806. console.time(counterName);
  6807. }
  6808. };
  6809. Tools._EndPerformanceConsole = function (counterName, condition) {
  6810. if (condition === void 0) { condition = true; }
  6811. if (!condition) {
  6812. return;
  6813. }
  6814. Tools._EndUserMark(counterName, condition);
  6815. if (console.time) {
  6816. console.timeEnd(counterName);
  6817. }
  6818. };
  6819. Object.defineProperty(Tools, "Now", {
  6820. get: function () {
  6821. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6822. return window.performance.now();
  6823. }
  6824. return new Date().getTime();
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. /**
  6830. * This method will return the name of the class used to create the instance of the given object.
  6831. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6832. * @param object the object to get the class name from
  6833. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6834. */
  6835. Tools.GetClassName = function (object, isType) {
  6836. if (isType === void 0) { isType = false; }
  6837. var name = null;
  6838. if (!isType && object.getClassName) {
  6839. name = object.getClassName();
  6840. }
  6841. else {
  6842. if (object instanceof Object) {
  6843. var classObj = isType ? object : Object.getPrototypeOf(object);
  6844. name = classObj.constructor["__bjsclassName__"];
  6845. }
  6846. if (!name) {
  6847. name = typeof object;
  6848. }
  6849. }
  6850. return name;
  6851. };
  6852. Tools.First = function (array, predicate) {
  6853. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6854. var el = array_1[_i];
  6855. if (predicate(el)) {
  6856. return el;
  6857. }
  6858. }
  6859. return null;
  6860. };
  6861. /**
  6862. * This method will return the name of the full name of the class, including its owning module (if any).
  6863. * 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).
  6864. * @param object the object to get the class name from
  6865. * @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.
  6866. */
  6867. Tools.getFullClassName = function (object, isType) {
  6868. if (isType === void 0) { isType = false; }
  6869. var className = null;
  6870. var moduleName = null;
  6871. if (!isType && object.getClassName) {
  6872. className = object.getClassName();
  6873. }
  6874. else {
  6875. if (object instanceof Object) {
  6876. var classObj = isType ? object : Object.getPrototypeOf(object);
  6877. className = classObj.constructor["__bjsclassName__"];
  6878. moduleName = classObj.constructor["__bjsmoduleName__"];
  6879. }
  6880. if (!className) {
  6881. className = typeof object;
  6882. }
  6883. }
  6884. if (!className) {
  6885. return null;
  6886. }
  6887. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6888. };
  6889. /**
  6890. * 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.
  6891. * @param array
  6892. */
  6893. Tools.arrayOrStringFeeder = function (array) {
  6894. return function (index) {
  6895. if (index >= array.length) {
  6896. return null;
  6897. }
  6898. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6899. if (val && val.getHashCode) {
  6900. val = val.getHashCode();
  6901. }
  6902. if (typeof val === "string") {
  6903. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6904. }
  6905. return val;
  6906. };
  6907. };
  6908. /**
  6909. * Compute the hashCode of a stream of number
  6910. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6911. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6912. * @return the hash code computed
  6913. */
  6914. Tools.hashCodeFromStream = function (feeder) {
  6915. // Based from here: http://stackoverflow.com/a/7616484/802124
  6916. var hash = 0;
  6917. var index = 0;
  6918. var chr = feeder(index++);
  6919. while (chr != null) {
  6920. hash = ((hash << 5) - hash) + chr;
  6921. hash |= 0; // Convert to 32bit integer
  6922. chr = feeder(index++);
  6923. }
  6924. return hash;
  6925. };
  6926. Tools.BaseUrl = "";
  6927. Tools.CorsBehavior = "anonymous";
  6928. Tools.UseFallbackTexture = true;
  6929. /**
  6930. * Use this object to register external classes like custom textures or material
  6931. * to allow the laoders to instantiate them
  6932. */
  6933. Tools.RegisteredExternalClasses = {};
  6934. // Used in case of a texture loading problem
  6935. 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";
  6936. Tools.PreprocessUrl = function (url) {
  6937. return url;
  6938. };
  6939. // Logs
  6940. Tools._NoneLogLevel = 0;
  6941. Tools._MessageLogLevel = 1;
  6942. Tools._WarningLogLevel = 2;
  6943. Tools._ErrorLogLevel = 4;
  6944. Tools._LogCache = "";
  6945. Tools.errorsCount = 0;
  6946. Tools.Log = Tools._LogEnabled;
  6947. Tools.Warn = Tools._WarnEnabled;
  6948. Tools.Error = Tools._ErrorEnabled;
  6949. // Performances
  6950. Tools._PerformanceNoneLogLevel = 0;
  6951. Tools._PerformanceUserMarkLogLevel = 1;
  6952. Tools._PerformanceConsoleLogLevel = 2;
  6953. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6954. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6955. return Tools;
  6956. }());
  6957. BABYLON.Tools = Tools;
  6958. /**
  6959. * This class is used to track a performance counter which is number based.
  6960. * The user has access to many properties which give statistics of different nature
  6961. *
  6962. * The implementer can track two kinds of Performance Counter: time and count
  6963. * 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.
  6964. * 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.
  6965. */
  6966. var PerfCounter = /** @class */ (function () {
  6967. function PerfCounter() {
  6968. this._startMonitoringTime = 0;
  6969. this._min = 0;
  6970. this._max = 0;
  6971. this._average = 0;
  6972. this._lastSecAverage = 0;
  6973. this._current = 0;
  6974. this._totalValueCount = 0;
  6975. this._totalAccumulated = 0;
  6976. this._lastSecAccumulated = 0;
  6977. this._lastSecTime = 0;
  6978. this._lastSecValueCount = 0;
  6979. }
  6980. Object.defineProperty(PerfCounter.prototype, "min", {
  6981. /**
  6982. * Returns the smallest value ever
  6983. */
  6984. get: function () {
  6985. return this._min;
  6986. },
  6987. enumerable: true,
  6988. configurable: true
  6989. });
  6990. Object.defineProperty(PerfCounter.prototype, "max", {
  6991. /**
  6992. * Returns the biggest value ever
  6993. */
  6994. get: function () {
  6995. return this._max;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Object.defineProperty(PerfCounter.prototype, "average", {
  7001. /**
  7002. * Returns the average value since the performance counter is running
  7003. */
  7004. get: function () {
  7005. return this._average;
  7006. },
  7007. enumerable: true,
  7008. configurable: true
  7009. });
  7010. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7011. /**
  7012. * Returns the average value of the last second the counter was monitored
  7013. */
  7014. get: function () {
  7015. return this._lastSecAverage;
  7016. },
  7017. enumerable: true,
  7018. configurable: true
  7019. });
  7020. Object.defineProperty(PerfCounter.prototype, "current", {
  7021. /**
  7022. * Returns the current value
  7023. */
  7024. get: function () {
  7025. return this._current;
  7026. },
  7027. enumerable: true,
  7028. configurable: true
  7029. });
  7030. Object.defineProperty(PerfCounter.prototype, "total", {
  7031. get: function () {
  7032. return this._totalAccumulated;
  7033. },
  7034. enumerable: true,
  7035. configurable: true
  7036. });
  7037. Object.defineProperty(PerfCounter.prototype, "count", {
  7038. get: function () {
  7039. return this._totalValueCount;
  7040. },
  7041. enumerable: true,
  7042. configurable: true
  7043. });
  7044. /**
  7045. * Call this method to start monitoring a new frame.
  7046. * 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.
  7047. */
  7048. PerfCounter.prototype.fetchNewFrame = function () {
  7049. this._totalValueCount++;
  7050. this._current = 0;
  7051. this._lastSecValueCount++;
  7052. };
  7053. /**
  7054. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7055. * @param newCount the count value to add to the monitored count
  7056. * @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.
  7057. */
  7058. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7059. if (!PerfCounter.Enabled) {
  7060. return;
  7061. }
  7062. this._current += newCount;
  7063. if (fetchResult) {
  7064. this._fetchResult();
  7065. }
  7066. };
  7067. /**
  7068. * Start monitoring this performance counter
  7069. */
  7070. PerfCounter.prototype.beginMonitoring = function () {
  7071. if (!PerfCounter.Enabled) {
  7072. return;
  7073. }
  7074. this._startMonitoringTime = Tools.Now;
  7075. };
  7076. /**
  7077. * Compute the time lapsed since the previous beginMonitoring() call.
  7078. * @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
  7079. */
  7080. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7081. if (newFrame === void 0) { newFrame = true; }
  7082. if (!PerfCounter.Enabled) {
  7083. return;
  7084. }
  7085. if (newFrame) {
  7086. this.fetchNewFrame();
  7087. }
  7088. var currentTime = Tools.Now;
  7089. this._current = currentTime - this._startMonitoringTime;
  7090. if (newFrame) {
  7091. this._fetchResult();
  7092. }
  7093. };
  7094. PerfCounter.prototype._fetchResult = function () {
  7095. this._totalAccumulated += this._current;
  7096. this._lastSecAccumulated += this._current;
  7097. // Min/Max update
  7098. this._min = Math.min(this._min, this._current);
  7099. this._max = Math.max(this._max, this._current);
  7100. this._average = this._totalAccumulated / this._totalValueCount;
  7101. // Reset last sec?
  7102. var now = Tools.Now;
  7103. if ((now - this._lastSecTime) > 1000) {
  7104. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7105. this._lastSecTime = now;
  7106. this._lastSecAccumulated = 0;
  7107. this._lastSecValueCount = 0;
  7108. }
  7109. };
  7110. PerfCounter.Enabled = true;
  7111. return PerfCounter;
  7112. }());
  7113. BABYLON.PerfCounter = PerfCounter;
  7114. /**
  7115. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7116. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7117. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7118. * @param name The name of the class, case should be preserved
  7119. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7120. */
  7121. function className(name, module) {
  7122. return function (target) {
  7123. target["__bjsclassName__"] = name;
  7124. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7125. };
  7126. }
  7127. BABYLON.className = className;
  7128. /**
  7129. * An implementation of a loop for asynchronous functions.
  7130. */
  7131. var AsyncLoop = /** @class */ (function () {
  7132. /**
  7133. * Constroctor.
  7134. * @param iterations the number of iterations.
  7135. * @param _fn the function to run each iteration
  7136. * @param _successCallback the callback that will be called upon succesful execution
  7137. * @param offset starting offset.
  7138. */
  7139. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7140. if (offset === void 0) { offset = 0; }
  7141. this.iterations = iterations;
  7142. this._fn = _fn;
  7143. this._successCallback = _successCallback;
  7144. this.index = offset - 1;
  7145. this._done = false;
  7146. }
  7147. /**
  7148. * Execute the next iteration. Must be called after the last iteration was finished.
  7149. */
  7150. AsyncLoop.prototype.executeNext = function () {
  7151. if (!this._done) {
  7152. if (this.index + 1 < this.iterations) {
  7153. ++this.index;
  7154. this._fn(this);
  7155. }
  7156. else {
  7157. this.breakLoop();
  7158. }
  7159. }
  7160. };
  7161. /**
  7162. * Break the loop and run the success callback.
  7163. */
  7164. AsyncLoop.prototype.breakLoop = function () {
  7165. this._done = true;
  7166. this._successCallback();
  7167. };
  7168. /**
  7169. * Helper function
  7170. */
  7171. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7172. if (offset === void 0) { offset = 0; }
  7173. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7174. loop.executeNext();
  7175. return loop;
  7176. };
  7177. /**
  7178. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7179. * @param iterations total number of iterations
  7180. * @param syncedIterations number of synchronous iterations in each async iteration.
  7181. * @param fn the function to call each iteration.
  7182. * @param callback a success call back that will be called when iterating stops.
  7183. * @param breakFunction a break condition (optional)
  7184. * @param timeout timeout settings for the setTimeout function. default - 0.
  7185. * @constructor
  7186. */
  7187. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7188. if (timeout === void 0) { timeout = 0; }
  7189. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7190. if (breakFunction && breakFunction())
  7191. loop.breakLoop();
  7192. else {
  7193. setTimeout(function () {
  7194. for (var i = 0; i < syncedIterations; ++i) {
  7195. var iteration = (loop.index * syncedIterations) + i;
  7196. if (iteration >= iterations)
  7197. break;
  7198. fn(iteration);
  7199. if (breakFunction && breakFunction()) {
  7200. loop.breakLoop();
  7201. break;
  7202. }
  7203. }
  7204. loop.executeNext();
  7205. }, timeout);
  7206. }
  7207. }, callback);
  7208. };
  7209. return AsyncLoop;
  7210. }());
  7211. BABYLON.AsyncLoop = AsyncLoop;
  7212. })(BABYLON || (BABYLON = {}));
  7213. //# sourceMappingURL=babylon.tools.js.map
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. var Internals;
  7217. (function (Internals) {
  7218. var _AlphaState = /** @class */ (function () {
  7219. /**
  7220. * Initializes the state.
  7221. */
  7222. function _AlphaState() {
  7223. this._isAlphaBlendDirty = false;
  7224. this._isBlendFunctionParametersDirty = false;
  7225. this._isBlendEquationParametersDirty = false;
  7226. this._isBlendConstantsDirty = false;
  7227. this._alphaBlend = false;
  7228. this._blendFunctionParameters = new Array(4);
  7229. this._blendEquationParameters = new Array(2);
  7230. this._blendConstants = new Array(4);
  7231. this.reset();
  7232. }
  7233. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7234. get: function () {
  7235. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7236. },
  7237. enumerable: true,
  7238. configurable: true
  7239. });
  7240. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7241. get: function () {
  7242. return this._alphaBlend;
  7243. },
  7244. set: function (value) {
  7245. if (this._alphaBlend === value) {
  7246. return;
  7247. }
  7248. this._alphaBlend = value;
  7249. this._isAlphaBlendDirty = true;
  7250. },
  7251. enumerable: true,
  7252. configurable: true
  7253. });
  7254. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7255. if (this._blendConstants[0] === r &&
  7256. this._blendConstants[1] === g &&
  7257. this._blendConstants[2] === b &&
  7258. this._blendConstants[3] === a) {
  7259. return;
  7260. }
  7261. this._blendConstants[0] = r;
  7262. this._blendConstants[1] = g;
  7263. this._blendConstants[2] = b;
  7264. this._blendConstants[3] = a;
  7265. this._isBlendConstantsDirty = true;
  7266. };
  7267. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7268. if (this._blendFunctionParameters[0] === value0 &&
  7269. this._blendFunctionParameters[1] === value1 &&
  7270. this._blendFunctionParameters[2] === value2 &&
  7271. this._blendFunctionParameters[3] === value3) {
  7272. return;
  7273. }
  7274. this._blendFunctionParameters[0] = value0;
  7275. this._blendFunctionParameters[1] = value1;
  7276. this._blendFunctionParameters[2] = value2;
  7277. this._blendFunctionParameters[3] = value3;
  7278. this._isBlendFunctionParametersDirty = true;
  7279. };
  7280. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7281. if (this._blendEquationParameters[0] === rgb &&
  7282. this._blendEquationParameters[1] === alpha) {
  7283. return;
  7284. }
  7285. this._blendEquationParameters[0] = rgb;
  7286. this._blendEquationParameters[1] = alpha;
  7287. this._isBlendEquationParametersDirty = true;
  7288. };
  7289. _AlphaState.prototype.reset = function () {
  7290. this._alphaBlend = false;
  7291. this._blendFunctionParameters[0] = null;
  7292. this._blendFunctionParameters[1] = null;
  7293. this._blendFunctionParameters[2] = null;
  7294. this._blendFunctionParameters[3] = null;
  7295. this._blendEquationParameters[0] = null;
  7296. this._blendEquationParameters[1] = null;
  7297. this._blendConstants[0] = null;
  7298. this._blendConstants[1] = null;
  7299. this._blendConstants[2] = null;
  7300. this._blendConstants[3] = null;
  7301. this._isAlphaBlendDirty = true;
  7302. this._isBlendFunctionParametersDirty = false;
  7303. this._isBlendEquationParametersDirty = false;
  7304. this._isBlendConstantsDirty = false;
  7305. };
  7306. _AlphaState.prototype.apply = function (gl) {
  7307. if (!this.isDirty) {
  7308. return;
  7309. }
  7310. // Alpha blend
  7311. if (this._isAlphaBlendDirty) {
  7312. if (this._alphaBlend) {
  7313. gl.enable(gl.BLEND);
  7314. }
  7315. else {
  7316. gl.disable(gl.BLEND);
  7317. }
  7318. this._isAlphaBlendDirty = false;
  7319. }
  7320. // Alpha function
  7321. if (this._isBlendFunctionParametersDirty) {
  7322. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7323. this._isBlendFunctionParametersDirty = false;
  7324. }
  7325. // Alpha equation
  7326. if (this._isBlendEquationParametersDirty) {
  7327. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7328. this._isBlendEquationParametersDirty = false;
  7329. }
  7330. // Constants
  7331. if (this._isBlendConstantsDirty) {
  7332. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7333. this._isBlendConstantsDirty = false;
  7334. }
  7335. };
  7336. return _AlphaState;
  7337. }());
  7338. Internals._AlphaState = _AlphaState;
  7339. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7340. })(BABYLON || (BABYLON = {}));
  7341. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7342. var BABYLON;
  7343. (function (BABYLON) {
  7344. var Internals;
  7345. (function (Internals) {
  7346. var _DepthCullingState = /** @class */ (function () {
  7347. /**
  7348. * Initializes the state.
  7349. */
  7350. function _DepthCullingState() {
  7351. this._isDepthTestDirty = false;
  7352. this._isDepthMaskDirty = false;
  7353. this._isDepthFuncDirty = false;
  7354. this._isCullFaceDirty = false;
  7355. this._isCullDirty = false;
  7356. this._isZOffsetDirty = false;
  7357. this.reset();
  7358. }
  7359. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7360. get: function () {
  7361. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7362. },
  7363. enumerable: true,
  7364. configurable: true
  7365. });
  7366. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7367. get: function () {
  7368. return this._zOffset;
  7369. },
  7370. set: function (value) {
  7371. if (this._zOffset === value) {
  7372. return;
  7373. }
  7374. this._zOffset = value;
  7375. this._isZOffsetDirty = true;
  7376. },
  7377. enumerable: true,
  7378. configurable: true
  7379. });
  7380. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7381. get: function () {
  7382. return this._cullFace;
  7383. },
  7384. set: function (value) {
  7385. if (this._cullFace === value) {
  7386. return;
  7387. }
  7388. this._cullFace = value;
  7389. this._isCullFaceDirty = true;
  7390. },
  7391. enumerable: true,
  7392. configurable: true
  7393. });
  7394. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7395. get: function () {
  7396. return this._cull;
  7397. },
  7398. set: function (value) {
  7399. if (this._cull === value) {
  7400. return;
  7401. }
  7402. this._cull = value;
  7403. this._isCullDirty = true;
  7404. },
  7405. enumerable: true,
  7406. configurable: true
  7407. });
  7408. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7409. get: function () {
  7410. return this._depthFunc;
  7411. },
  7412. set: function (value) {
  7413. if (this._depthFunc === value) {
  7414. return;
  7415. }
  7416. this._depthFunc = value;
  7417. this._isDepthFuncDirty = true;
  7418. },
  7419. enumerable: true,
  7420. configurable: true
  7421. });
  7422. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7423. get: function () {
  7424. return this._depthMask;
  7425. },
  7426. set: function (value) {
  7427. if (this._depthMask === value) {
  7428. return;
  7429. }
  7430. this._depthMask = value;
  7431. this._isDepthMaskDirty = true;
  7432. },
  7433. enumerable: true,
  7434. configurable: true
  7435. });
  7436. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7437. get: function () {
  7438. return this._depthTest;
  7439. },
  7440. set: function (value) {
  7441. if (this._depthTest === value) {
  7442. return;
  7443. }
  7444. this._depthTest = value;
  7445. this._isDepthTestDirty = true;
  7446. },
  7447. enumerable: true,
  7448. configurable: true
  7449. });
  7450. _DepthCullingState.prototype.reset = function () {
  7451. this._depthMask = true;
  7452. this._depthTest = true;
  7453. this._depthFunc = null;
  7454. this._cullFace = null;
  7455. this._cull = null;
  7456. this._zOffset = 0;
  7457. this._isDepthTestDirty = true;
  7458. this._isDepthMaskDirty = true;
  7459. this._isDepthFuncDirty = false;
  7460. this._isCullFaceDirty = false;
  7461. this._isCullDirty = false;
  7462. this._isZOffsetDirty = false;
  7463. };
  7464. _DepthCullingState.prototype.apply = function (gl) {
  7465. if (!this.isDirty) {
  7466. return;
  7467. }
  7468. // Cull
  7469. if (this._isCullDirty) {
  7470. if (this.cull) {
  7471. gl.enable(gl.CULL_FACE);
  7472. }
  7473. else {
  7474. gl.disable(gl.CULL_FACE);
  7475. }
  7476. this._isCullDirty = false;
  7477. }
  7478. // Cull face
  7479. if (this._isCullFaceDirty) {
  7480. gl.cullFace(this.cullFace);
  7481. this._isCullFaceDirty = false;
  7482. }
  7483. // Depth mask
  7484. if (this._isDepthMaskDirty) {
  7485. gl.depthMask(this.depthMask);
  7486. this._isDepthMaskDirty = false;
  7487. }
  7488. // Depth test
  7489. if (this._isDepthTestDirty) {
  7490. if (this.depthTest) {
  7491. gl.enable(gl.DEPTH_TEST);
  7492. }
  7493. else {
  7494. gl.disable(gl.DEPTH_TEST);
  7495. }
  7496. this._isDepthTestDirty = false;
  7497. }
  7498. // Depth func
  7499. if (this._isDepthFuncDirty) {
  7500. gl.depthFunc(this.depthFunc);
  7501. this._isDepthFuncDirty = false;
  7502. }
  7503. // zOffset
  7504. if (this._isZOffsetDirty) {
  7505. if (this.zOffset) {
  7506. gl.enable(gl.POLYGON_OFFSET_FILL);
  7507. gl.polygonOffset(this.zOffset, 0);
  7508. }
  7509. else {
  7510. gl.disable(gl.POLYGON_OFFSET_FILL);
  7511. }
  7512. this._isZOffsetDirty = false;
  7513. }
  7514. };
  7515. return _DepthCullingState;
  7516. }());
  7517. Internals._DepthCullingState = _DepthCullingState;
  7518. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7519. })(BABYLON || (BABYLON = {}));
  7520. //# sourceMappingURL=babylon.depthCullingState.js.map
  7521. var BABYLON;
  7522. (function (BABYLON) {
  7523. var Internals;
  7524. (function (Internals) {
  7525. var _StencilState = /** @class */ (function () {
  7526. function _StencilState() {
  7527. this._isStencilTestDirty = false;
  7528. this._isStencilMaskDirty = false;
  7529. this._isStencilFuncDirty = false;
  7530. this._isStencilOpDirty = false;
  7531. this.reset();
  7532. }
  7533. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7534. get: function () {
  7535. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7541. get: function () {
  7542. return this._stencilFunc;
  7543. },
  7544. set: function (value) {
  7545. if (this._stencilFunc === value) {
  7546. return;
  7547. }
  7548. this._stencilFunc = value;
  7549. this._isStencilFuncDirty = true;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7555. get: function () {
  7556. return this._stencilFuncRef;
  7557. },
  7558. set: function (value) {
  7559. if (this._stencilFuncRef === value) {
  7560. return;
  7561. }
  7562. this._stencilFuncRef = value;
  7563. this._isStencilFuncDirty = true;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7569. get: function () {
  7570. return this._stencilFuncMask;
  7571. },
  7572. set: function (value) {
  7573. if (this._stencilFuncMask === value) {
  7574. return;
  7575. }
  7576. this._stencilFuncMask = value;
  7577. this._isStencilFuncDirty = true;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7583. get: function () {
  7584. return this._stencilOpStencilFail;
  7585. },
  7586. set: function (value) {
  7587. if (this._stencilOpStencilFail === value) {
  7588. return;
  7589. }
  7590. this._stencilOpStencilFail = value;
  7591. this._isStencilOpDirty = true;
  7592. },
  7593. enumerable: true,
  7594. configurable: true
  7595. });
  7596. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7597. get: function () {
  7598. return this._stencilOpDepthFail;
  7599. },
  7600. set: function (value) {
  7601. if (this._stencilOpDepthFail === value) {
  7602. return;
  7603. }
  7604. this._stencilOpDepthFail = value;
  7605. this._isStencilOpDirty = true;
  7606. },
  7607. enumerable: true,
  7608. configurable: true
  7609. });
  7610. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7611. get: function () {
  7612. return this._stencilOpStencilDepthPass;
  7613. },
  7614. set: function (value) {
  7615. if (this._stencilOpStencilDepthPass === value) {
  7616. return;
  7617. }
  7618. this._stencilOpStencilDepthPass = value;
  7619. this._isStencilOpDirty = true;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7625. get: function () {
  7626. return this._stencilMask;
  7627. },
  7628. set: function (value) {
  7629. if (this._stencilMask === value) {
  7630. return;
  7631. }
  7632. this._stencilMask = value;
  7633. this._isStencilMaskDirty = true;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7639. get: function () {
  7640. return this._stencilTest;
  7641. },
  7642. set: function (value) {
  7643. if (this._stencilTest === value) {
  7644. return;
  7645. }
  7646. this._stencilTest = value;
  7647. this._isStencilTestDirty = true;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. _StencilState.prototype.reset = function () {
  7653. this._stencilTest = false;
  7654. this._stencilMask = 0xFF;
  7655. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7656. this._stencilFuncRef = 1;
  7657. this._stencilFuncMask = 0xFF;
  7658. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7659. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7660. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7661. this._isStencilTestDirty = true;
  7662. this._isStencilMaskDirty = true;
  7663. this._isStencilFuncDirty = true;
  7664. this._isStencilOpDirty = true;
  7665. };
  7666. _StencilState.prototype.apply = function (gl) {
  7667. if (!this.isDirty) {
  7668. return;
  7669. }
  7670. // Stencil test
  7671. if (this._isStencilTestDirty) {
  7672. if (this.stencilTest) {
  7673. gl.enable(gl.STENCIL_TEST);
  7674. }
  7675. else {
  7676. gl.disable(gl.STENCIL_TEST);
  7677. }
  7678. this._isStencilTestDirty = false;
  7679. }
  7680. // Stencil mask
  7681. if (this._isStencilMaskDirty) {
  7682. gl.stencilMask(this.stencilMask);
  7683. this._isStencilMaskDirty = false;
  7684. }
  7685. // Stencil func
  7686. if (this._isStencilFuncDirty) {
  7687. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7688. this._isStencilFuncDirty = false;
  7689. }
  7690. // Stencil op
  7691. if (this._isStencilOpDirty) {
  7692. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7693. this._isStencilOpDirty = false;
  7694. }
  7695. };
  7696. return _StencilState;
  7697. }());
  7698. Internals._StencilState = _StencilState;
  7699. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7700. })(BABYLON || (BABYLON = {}));
  7701. //# sourceMappingURL=babylon.stencilState.js.map
  7702. var BABYLON;
  7703. (function (BABYLON) {
  7704. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7705. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7706. };
  7707. var compileRawShader = function (gl, source, type) {
  7708. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7709. gl.shaderSource(shader, source);
  7710. gl.compileShader(shader);
  7711. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7712. var log = gl.getShaderInfoLog(shader);
  7713. if (log) {
  7714. throw new Error(log);
  7715. }
  7716. }
  7717. if (!shader) {
  7718. throw new Error("Something went wrong while compile the shader.");
  7719. }
  7720. return shader;
  7721. };
  7722. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7723. var magFilter = gl.NEAREST;
  7724. var minFilter = gl.NEAREST;
  7725. switch (samplingMode) {
  7726. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7727. magFilter = gl.LINEAR;
  7728. if (generateMipMaps) {
  7729. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7730. }
  7731. else {
  7732. minFilter = gl.LINEAR;
  7733. }
  7734. break;
  7735. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7736. magFilter = gl.LINEAR;
  7737. if (generateMipMaps) {
  7738. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7739. }
  7740. else {
  7741. minFilter = gl.LINEAR;
  7742. }
  7743. break;
  7744. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7745. magFilter = gl.NEAREST;
  7746. if (generateMipMaps) {
  7747. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7748. }
  7749. else {
  7750. minFilter = gl.NEAREST;
  7751. }
  7752. break;
  7753. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7754. magFilter = gl.NEAREST;
  7755. if (generateMipMaps) {
  7756. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7757. }
  7758. else {
  7759. minFilter = gl.NEAREST;
  7760. }
  7761. break;
  7762. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7763. magFilter = gl.NEAREST;
  7764. if (generateMipMaps) {
  7765. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7766. }
  7767. else {
  7768. minFilter = gl.LINEAR;
  7769. }
  7770. break;
  7771. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7772. magFilter = gl.NEAREST;
  7773. if (generateMipMaps) {
  7774. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7775. }
  7776. else {
  7777. minFilter = gl.LINEAR;
  7778. }
  7779. break;
  7780. case BABYLON.Texture.NEAREST_LINEAR:
  7781. magFilter = gl.NEAREST;
  7782. minFilter = gl.LINEAR;
  7783. break;
  7784. case BABYLON.Texture.NEAREST_NEAREST:
  7785. magFilter = gl.NEAREST;
  7786. minFilter = gl.NEAREST;
  7787. break;
  7788. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7789. magFilter = gl.LINEAR;
  7790. if (generateMipMaps) {
  7791. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7792. }
  7793. else {
  7794. minFilter = gl.NEAREST;
  7795. }
  7796. break;
  7797. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7798. magFilter = gl.LINEAR;
  7799. if (generateMipMaps) {
  7800. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7801. }
  7802. else {
  7803. minFilter = gl.NEAREST;
  7804. }
  7805. break;
  7806. case BABYLON.Texture.LINEAR_LINEAR:
  7807. magFilter = gl.LINEAR;
  7808. minFilter = gl.LINEAR;
  7809. break;
  7810. case BABYLON.Texture.LINEAR_NEAREST:
  7811. magFilter = gl.LINEAR;
  7812. minFilter = gl.NEAREST;
  7813. break;
  7814. }
  7815. return {
  7816. min: minFilter,
  7817. mag: magFilter
  7818. };
  7819. };
  7820. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7821. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7822. var img;
  7823. var onload = function () {
  7824. loadedImages[index] = img;
  7825. loadedImages._internalCount++;
  7826. if (scene) {
  7827. scene._removePendingData(img);
  7828. }
  7829. if (loadedImages._internalCount === 6) {
  7830. onfinish(loadedImages);
  7831. }
  7832. };
  7833. var onerror = function (message, exception) {
  7834. if (scene) {
  7835. scene._removePendingData(img);
  7836. }
  7837. if (onErrorCallBack) {
  7838. onErrorCallBack(message, exception);
  7839. }
  7840. };
  7841. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7842. if (scene) {
  7843. scene._addPendingData(img);
  7844. }
  7845. };
  7846. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7847. if (onError === void 0) { onError = null; }
  7848. var loadedImages = [];
  7849. loadedImages._internalCount = 0;
  7850. for (var index = 0; index < 6; index++) {
  7851. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7852. }
  7853. };
  7854. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7855. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7856. var onload = function (data) {
  7857. loadedFiles[index] = data;
  7858. loadedFiles._internalCount++;
  7859. if (loadedFiles._internalCount === 6) {
  7860. onfinish(loadedFiles);
  7861. }
  7862. };
  7863. var onerror = function (request, exception) {
  7864. if (onErrorCallBack && request) {
  7865. onErrorCallBack(request.status + " " + request.statusText, exception);
  7866. }
  7867. };
  7868. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7869. };
  7870. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7871. if (onError === void 0) { onError = null; }
  7872. var loadedFiles = [];
  7873. loadedFiles._internalCount = 0;
  7874. for (var index = 0; index < 6; index++) {
  7875. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7876. }
  7877. };
  7878. var BufferPointer = /** @class */ (function () {
  7879. function BufferPointer() {
  7880. }
  7881. return BufferPointer;
  7882. }());
  7883. var InstancingAttributeInfo = /** @class */ (function () {
  7884. function InstancingAttributeInfo() {
  7885. }
  7886. return InstancingAttributeInfo;
  7887. }());
  7888. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7889. /**
  7890. * Define options used to create a render target texture
  7891. */
  7892. var RenderTargetCreationOptions = /** @class */ (function () {
  7893. function RenderTargetCreationOptions() {
  7894. }
  7895. return RenderTargetCreationOptions;
  7896. }());
  7897. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7898. /**
  7899. * Regroup several parameters relative to the browser in use
  7900. */
  7901. var EngineCapabilities = /** @class */ (function () {
  7902. function EngineCapabilities() {
  7903. }
  7904. return EngineCapabilities;
  7905. }());
  7906. BABYLON.EngineCapabilities = EngineCapabilities;
  7907. /**
  7908. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7909. */
  7910. var Engine = /** @class */ (function () {
  7911. /**
  7912. * @constructor
  7913. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7914. * @param {boolean} [antialias] - enable antialias
  7915. * @param options - further options to be sent to the getContext function
  7916. */
  7917. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7918. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7919. var _this = this;
  7920. // Public members
  7921. this.forcePOTTextures = false;
  7922. this.isFullscreen = false;
  7923. this.isPointerLock = false;
  7924. this.cullBackFaces = true;
  7925. this.renderEvenInBackground = true;
  7926. this.preventCacheWipeBetweenFrames = false;
  7927. // To enable/disable IDB support and avoid XHR on .manifest
  7928. this.enableOfflineSupport = false;
  7929. this.scenes = new Array();
  7930. this.postProcesses = new Array();
  7931. // Observables
  7932. /**
  7933. * Observable event triggered each time the rendering canvas is resized
  7934. */
  7935. this.onResizeObservable = new BABYLON.Observable();
  7936. /**
  7937. * Observable event triggered each time the canvas loses focus
  7938. */
  7939. this.onCanvasBlurObservable = new BABYLON.Observable();
  7940. /**
  7941. * Observable event triggered each time the canvas gains focus
  7942. */
  7943. this.onCanvasFocusObservable = new BABYLON.Observable();
  7944. /**
  7945. * Observable event triggered each time the canvas receives pointerout event
  7946. */
  7947. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7948. /**
  7949. * Observable event triggered before each texture is initialized
  7950. */
  7951. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7952. //WebVR
  7953. this._vrDisplay = undefined;
  7954. this._vrSupported = false;
  7955. this._vrExclusivePointerMode = false;
  7956. // Uniform buffers list
  7957. this.disableUniformBuffers = false;
  7958. this._uniformBuffers = new Array();
  7959. // Observables
  7960. /**
  7961. * Observable raised when the engine begins a new frame
  7962. */
  7963. this.onBeginFrameObservable = new BABYLON.Observable();
  7964. /**
  7965. * Observable raised when the engine ends the current frame
  7966. */
  7967. this.onEndFrameObservable = new BABYLON.Observable();
  7968. /**
  7969. * Observable raised when the engine is about to compile a shader
  7970. */
  7971. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7972. /**
  7973. * Observable raised when the engine has jsut compiled a shader
  7974. */
  7975. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7976. this._windowIsBackground = false;
  7977. this._webGLVersion = 1.0;
  7978. this._badOS = false;
  7979. this._badDesktopOS = false;
  7980. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7981. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7982. this.onVRRequestPresentStart = new BABYLON.Observable();
  7983. this._colorWrite = true;
  7984. this._drawCalls = new BABYLON.PerfCounter();
  7985. this._renderingQueueLaunched = false;
  7986. this._activeRenderLoops = new Array();
  7987. // Deterministic lockstepMaxSteps
  7988. this._deterministicLockstep = false;
  7989. this._lockstepMaxSteps = 4;
  7990. // Lost context
  7991. this.onContextLostObservable = new BABYLON.Observable();
  7992. this.onContextRestoredObservable = new BABYLON.Observable();
  7993. this._contextWasLost = false;
  7994. this._doNotHandleContextLost = false;
  7995. // FPS
  7996. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7997. this._fps = 60;
  7998. this._deltaTime = 0;
  7999. /**
  8000. * Turn this value on if you want to pause FPS computation when in background
  8001. */
  8002. this.disablePerformanceMonitorInBackground = false;
  8003. // States
  8004. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8005. this._stencilState = new BABYLON.Internals._StencilState();
  8006. this._alphaState = new BABYLON.Internals._AlphaState();
  8007. this._alphaMode = Engine.ALPHA_DISABLE;
  8008. // Cache
  8009. this._internalTexturesCache = new Array();
  8010. this._boundTexturesCache = {};
  8011. this._compiledEffects = {};
  8012. this._vertexAttribArraysEnabled = [];
  8013. this._uintIndicesCurrentlySet = false;
  8014. this._currentBoundBuffer = new Array();
  8015. this._currentBufferPointers = new Array();
  8016. this._currentInstanceLocations = new Array();
  8017. this._currentInstanceBuffers = new Array();
  8018. this._vaoRecordInProgress = false;
  8019. this._mustWipeVertexAttributes = false;
  8020. // Hardware supported Compressed Textures
  8021. this._texturesSupported = new Array();
  8022. this._onVRFullScreenTriggered = function () {
  8023. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8024. //get the old size before we change
  8025. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8026. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8027. //get the width and height, change the render size
  8028. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8029. _this.setHardwareScalingLevel(1);
  8030. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8031. }
  8032. else {
  8033. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8034. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8035. }
  8036. };
  8037. var canvas = null;
  8038. Engine.Instances.push(this);
  8039. if (!canvasOrContext) {
  8040. return;
  8041. }
  8042. options = options || {};
  8043. if (canvasOrContext.getContext) {
  8044. canvas = canvasOrContext;
  8045. this._renderingCanvas = canvas;
  8046. if (antialias != null) {
  8047. options.antialias = antialias;
  8048. }
  8049. if (options.deterministicLockstep === undefined) {
  8050. options.deterministicLockstep = false;
  8051. }
  8052. if (options.lockstepMaxSteps === undefined) {
  8053. options.lockstepMaxSteps = 4;
  8054. }
  8055. if (options.preserveDrawingBuffer === undefined) {
  8056. options.preserveDrawingBuffer = false;
  8057. }
  8058. if (options.audioEngine === undefined) {
  8059. options.audioEngine = true;
  8060. }
  8061. if (options.stencil === undefined) {
  8062. options.stencil = true;
  8063. }
  8064. this._deterministicLockstep = options.deterministicLockstep;
  8065. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8066. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8067. // GL
  8068. if (!options.disableWebGL2Support) {
  8069. try {
  8070. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8071. if (this._gl) {
  8072. this._webGLVersion = 2.0;
  8073. }
  8074. }
  8075. catch (e) {
  8076. // Do nothing
  8077. }
  8078. }
  8079. if (!this._gl) {
  8080. if (!canvas) {
  8081. throw new Error("The provided canvas is null or undefined.");
  8082. }
  8083. try {
  8084. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8085. }
  8086. catch (e) {
  8087. throw new Error("WebGL not supported");
  8088. }
  8089. }
  8090. if (!this._gl) {
  8091. throw new Error("WebGL not supported");
  8092. }
  8093. this._onCanvasFocus = function () {
  8094. _this.onCanvasFocusObservable.notifyObservers(_this);
  8095. };
  8096. this._onCanvasBlur = function () {
  8097. _this.onCanvasBlurObservable.notifyObservers(_this);
  8098. };
  8099. canvas.addEventListener("focus", this._onCanvasFocus);
  8100. canvas.addEventListener("blur", this._onCanvasBlur);
  8101. this._onBlur = function () {
  8102. if (_this.disablePerformanceMonitorInBackground) {
  8103. _this._performanceMonitor.disable();
  8104. }
  8105. _this._windowIsBackground = true;
  8106. };
  8107. this._onFocus = function () {
  8108. if (_this.disablePerformanceMonitorInBackground) {
  8109. _this._performanceMonitor.enable();
  8110. }
  8111. _this._windowIsBackground = false;
  8112. };
  8113. this._onCanvasPointerOut = function () {
  8114. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8115. };
  8116. window.addEventListener("blur", this._onBlur);
  8117. window.addEventListener("focus", this._onFocus);
  8118. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8119. // Context lost
  8120. if (!this._doNotHandleContextLost) {
  8121. this._onContextLost = function (evt) {
  8122. evt.preventDefault();
  8123. _this._contextWasLost = true;
  8124. BABYLON.Tools.Warn("WebGL context lost.");
  8125. _this.onContextLostObservable.notifyObservers(_this);
  8126. };
  8127. this._onContextRestored = function (evt) {
  8128. // Adding a timeout to avoid race condition at browser level
  8129. setTimeout(function () {
  8130. // Rebuild gl context
  8131. _this._initGLContext();
  8132. // Rebuild effects
  8133. _this._rebuildEffects();
  8134. // Rebuild textures
  8135. _this._rebuildInternalTextures();
  8136. // Rebuild buffers
  8137. _this._rebuildBuffers();
  8138. // Cache
  8139. _this.wipeCaches(true);
  8140. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8141. _this.onContextRestoredObservable.notifyObservers(_this);
  8142. _this._contextWasLost = false;
  8143. }, 0);
  8144. };
  8145. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8146. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8147. }
  8148. }
  8149. else {
  8150. this._gl = canvasOrContext;
  8151. this._renderingCanvas = this._gl.canvas;
  8152. if (this._gl.renderbufferStorageMultisample) {
  8153. this._webGLVersion = 2.0;
  8154. }
  8155. options.stencil = this._gl.getContextAttributes().stencil;
  8156. }
  8157. // Viewport
  8158. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8159. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8160. this.resize();
  8161. this._isStencilEnable = options.stencil ? true : false;
  8162. this._initGLContext();
  8163. if (canvas) {
  8164. // Fullscreen
  8165. this._onFullscreenChange = function () {
  8166. if (document.fullscreen !== undefined) {
  8167. _this.isFullscreen = document.fullscreen;
  8168. }
  8169. else if (document.mozFullScreen !== undefined) {
  8170. _this.isFullscreen = document.mozFullScreen;
  8171. }
  8172. else if (document.webkitIsFullScreen !== undefined) {
  8173. _this.isFullscreen = document.webkitIsFullScreen;
  8174. }
  8175. else if (document.msIsFullScreen !== undefined) {
  8176. _this.isFullscreen = document.msIsFullScreen;
  8177. }
  8178. // Pointer lock
  8179. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8180. canvas.requestPointerLock = canvas.requestPointerLock ||
  8181. canvas.msRequestPointerLock ||
  8182. canvas.mozRequestPointerLock ||
  8183. canvas.webkitRequestPointerLock;
  8184. if (canvas.requestPointerLock) {
  8185. canvas.requestPointerLock();
  8186. }
  8187. }
  8188. };
  8189. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8190. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8191. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8192. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8193. // Pointer lock
  8194. this._onPointerLockChange = function () {
  8195. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8196. document.webkitPointerLockElement === canvas ||
  8197. document.msPointerLockElement === canvas ||
  8198. document.pointerLockElement === canvas);
  8199. };
  8200. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8201. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8202. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8203. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8204. this._onVRDisplayPointerRestricted = function () {
  8205. if (canvas) {
  8206. canvas.requestPointerLock();
  8207. }
  8208. };
  8209. this._onVRDisplayPointerUnrestricted = function () {
  8210. document.exitPointerLock();
  8211. };
  8212. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8213. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8214. }
  8215. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8216. Engine.audioEngine = new BABYLON.AudioEngine();
  8217. }
  8218. // Prepare buffer pointers
  8219. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8220. this._currentBufferPointers[i] = new BufferPointer();
  8221. }
  8222. // Load WebVR Devices
  8223. if (options.autoEnableWebVR) {
  8224. this.initWebVR();
  8225. }
  8226. // Detect if we are running on a faulty buggy OS.
  8227. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8228. // Detect if we are running on a faulty buggy desktop OS.
  8229. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8230. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8231. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8232. }
  8233. Object.defineProperty(Engine, "LastCreatedEngine", {
  8234. get: function () {
  8235. if (Engine.Instances.length === 0) {
  8236. return null;
  8237. }
  8238. return Engine.Instances[Engine.Instances.length - 1];
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Engine, "LastCreatedScene", {
  8244. get: function () {
  8245. var lastCreatedEngine = Engine.LastCreatedEngine;
  8246. if (!lastCreatedEngine) {
  8247. return null;
  8248. }
  8249. if (lastCreatedEngine.scenes.length === 0) {
  8250. return null;
  8251. }
  8252. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. /**
  8258. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8259. */
  8260. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8261. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8262. var engine = Engine.Instances[engineIndex];
  8263. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8264. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8265. }
  8266. }
  8267. };
  8268. Object.defineProperty(Engine, "NEVER", {
  8269. get: function () {
  8270. return Engine._NEVER;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALWAYS", {
  8276. get: function () {
  8277. return Engine._ALWAYS;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "LESS", {
  8283. get: function () {
  8284. return Engine._LESS;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "EQUAL", {
  8290. get: function () {
  8291. return Engine._EQUAL;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "LEQUAL", {
  8297. get: function () {
  8298. return Engine._LEQUAL;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "GREATER", {
  8304. get: function () {
  8305. return Engine._GREATER;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "GEQUAL", {
  8311. get: function () {
  8312. return Engine._GEQUAL;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "NOTEQUAL", {
  8318. get: function () {
  8319. return Engine._NOTEQUAL;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "KEEP", {
  8325. get: function () {
  8326. return Engine._KEEP;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "REPLACE", {
  8332. get: function () {
  8333. return Engine._REPLACE;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "INCR", {
  8339. get: function () {
  8340. return Engine._INCR;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "DECR", {
  8346. get: function () {
  8347. return Engine._DECR;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "INVERT", {
  8353. get: function () {
  8354. return Engine._INVERT;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "INCR_WRAP", {
  8360. get: function () {
  8361. return Engine._INCR_WRAP;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DECR_WRAP", {
  8367. get: function () {
  8368. return Engine._DECR_WRAP;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8374. get: function () {
  8375. return Engine._ALPHA_DISABLE;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8381. get: function () {
  8382. return Engine._ALPHA_ONEONE;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "ALPHA_ADD", {
  8388. get: function () {
  8389. return Engine._ALPHA_ADD;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8395. get: function () {
  8396. return Engine._ALPHA_COMBINE;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8402. get: function () {
  8403. return Engine._ALPHA_SUBTRACT;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8409. get: function () {
  8410. return Engine._ALPHA_MULTIPLY;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8416. get: function () {
  8417. return Engine._ALPHA_MAXIMIZED;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8423. get: function () {
  8424. return Engine._ALPHA_PREMULTIPLIED;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8430. get: function () {
  8431. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8437. get: function () {
  8438. return Engine._ALPHA_INTERPOLATE;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8444. get: function () {
  8445. return Engine._ALPHA_SCREENMODE;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8451. get: function () {
  8452. return Engine._DELAYLOADSTATE_NONE;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8458. get: function () {
  8459. return Engine._DELAYLOADSTATE_LOADED;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8465. get: function () {
  8466. return Engine._DELAYLOADSTATE_LOADING;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8472. get: function () {
  8473. return Engine._DELAYLOADSTATE_NOTLOADED;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8479. get: function () {
  8480. return Engine._TEXTUREFORMAT_ALPHA;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8486. get: function () {
  8487. return Engine._TEXTUREFORMAT_LUMINANCE;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8493. get: function () {
  8494. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8500. get: function () {
  8501. return Engine._TEXTUREFORMAT_RGB;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8507. get: function () {
  8508. return Engine._TEXTUREFORMAT_RGBA;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8514. get: function () {
  8515. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8521. get: function () {
  8522. return Engine._TEXTURETYPE_FLOAT;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8528. get: function () {
  8529. return Engine._TEXTURETYPE_HALF_FLOAT;
  8530. },
  8531. enumerable: true,
  8532. configurable: true
  8533. });
  8534. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8535. get: function () {
  8536. return Engine._SCALEMODE_FLOOR;
  8537. },
  8538. enumerable: true,
  8539. configurable: true
  8540. });
  8541. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8542. get: function () {
  8543. return Engine._SCALEMODE_NEAREST;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8549. get: function () {
  8550. return Engine._SCALEMODE_CEILING;
  8551. },
  8552. enumerable: true,
  8553. configurable: true
  8554. });
  8555. Object.defineProperty(Engine, "Version", {
  8556. get: function () {
  8557. return "3.1-beta-6";
  8558. },
  8559. enumerable: true,
  8560. configurable: true
  8561. });
  8562. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8563. get: function () {
  8564. return this._vrExclusivePointerMode;
  8565. },
  8566. enumerable: true,
  8567. configurable: true
  8568. });
  8569. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8570. get: function () {
  8571. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8577. get: function () {
  8578. return this._webGLVersion < 2 || this.forcePOTTextures;
  8579. },
  8580. enumerable: true,
  8581. configurable: true
  8582. });
  8583. Object.defineProperty(Engine.prototype, "badOS", {
  8584. get: function () {
  8585. return this._badOS;
  8586. },
  8587. enumerable: true,
  8588. configurable: true
  8589. });
  8590. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8591. get: function () {
  8592. return this._badDesktopOS;
  8593. },
  8594. enumerable: true,
  8595. configurable: true
  8596. });
  8597. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8598. get: function () {
  8599. return this._performanceMonitor;
  8600. },
  8601. enumerable: true,
  8602. configurable: true
  8603. });
  8604. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8605. get: function () {
  8606. return this._texturesSupported;
  8607. },
  8608. enumerable: true,
  8609. configurable: true
  8610. });
  8611. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8612. get: function () {
  8613. return this._textureFormatInUse;
  8614. },
  8615. enumerable: true,
  8616. configurable: true
  8617. });
  8618. Object.defineProperty(Engine.prototype, "currentViewport", {
  8619. get: function () {
  8620. return this._cachedViewport;
  8621. },
  8622. enumerable: true,
  8623. configurable: true
  8624. });
  8625. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8626. // Empty texture
  8627. get: function () {
  8628. if (!this._emptyTexture) {
  8629. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8630. }
  8631. return this._emptyTexture;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8637. get: function () {
  8638. if (!this._emptyTexture3D) {
  8639. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8640. }
  8641. return this._emptyTexture3D;
  8642. },
  8643. enumerable: true,
  8644. configurable: true
  8645. });
  8646. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8647. get: function () {
  8648. if (!this._emptyCubeTexture) {
  8649. var faceData = new Uint8Array(4);
  8650. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8651. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8652. }
  8653. return this._emptyCubeTexture;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Engine.prototype._rebuildInternalTextures = function () {
  8659. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8660. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8661. var internalTexture = currentState_1[_i];
  8662. internalTexture._rebuild();
  8663. }
  8664. };
  8665. Engine.prototype._rebuildEffects = function () {
  8666. for (var key in this._compiledEffects) {
  8667. var effect = this._compiledEffects[key];
  8668. effect._prepareEffect();
  8669. }
  8670. BABYLON.Effect.ResetCache();
  8671. };
  8672. Engine.prototype._rebuildBuffers = function () {
  8673. // Index / Vertex
  8674. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8675. var scene = _a[_i];
  8676. scene.resetCachedMaterial();
  8677. scene._rebuildGeometries();
  8678. scene._rebuildTextures();
  8679. }
  8680. // Uniforms
  8681. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8682. var uniformBuffer = _c[_b];
  8683. uniformBuffer._rebuild();
  8684. }
  8685. };
  8686. Engine.prototype._initGLContext = function () {
  8687. // Caps
  8688. this._caps = new EngineCapabilities();
  8689. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8690. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8691. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8692. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8693. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8694. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8695. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8696. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8697. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8698. // Infos
  8699. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8700. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8701. if (rendererInfo != null) {
  8702. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8703. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8704. }
  8705. if (!this._glVendor) {
  8706. this._glVendor = "Unknown vendor";
  8707. }
  8708. if (!this._glRenderer) {
  8709. this._glRenderer = "Unknown renderer";
  8710. }
  8711. // Constants
  8712. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8713. if (this._gl.RGBA16F !== 0x881A) {
  8714. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8715. }
  8716. if (this._gl.RGBA32F !== 0x8814) {
  8717. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8718. }
  8719. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8720. this._gl.DEPTH24_STENCIL8 = 35056;
  8721. }
  8722. // Extensions
  8723. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8724. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8725. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8726. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8727. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8728. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8729. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8730. 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');
  8731. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8732. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8733. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8734. this._caps.highPrecisionShaderSupported = true;
  8735. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8736. if (this._caps.timerQuery) {
  8737. if (this._webGLVersion === 1) {
  8738. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8739. }
  8740. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8741. }
  8742. // Checks if some of the format renders first to allow the use of webgl inspector.
  8743. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8744. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8745. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8746. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8747. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8748. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8749. if (this._webGLVersion > 1) {
  8750. this._gl.HALF_FLOAT_OES = 0x140B;
  8751. }
  8752. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8753. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8754. // Draw buffers
  8755. if (this._webGLVersion > 1) {
  8756. this._caps.drawBuffersExtension = true;
  8757. }
  8758. else {
  8759. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8760. if (drawBuffersExtension !== null) {
  8761. this._caps.drawBuffersExtension = true;
  8762. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8763. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8764. for (var i = 0; i < 16; i++) {
  8765. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8766. }
  8767. }
  8768. else {
  8769. this._caps.drawBuffersExtension = false;
  8770. }
  8771. }
  8772. // Depth Texture
  8773. if (this._webGLVersion > 1) {
  8774. this._caps.depthTextureExtension = true;
  8775. }
  8776. else {
  8777. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8778. if (depthTextureExtension != null) {
  8779. this._caps.depthTextureExtension = true;
  8780. }
  8781. }
  8782. // Vertex array object
  8783. if (this._webGLVersion > 1) {
  8784. this._caps.vertexArrayObject = true;
  8785. }
  8786. else {
  8787. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8788. if (vertexArrayObjectExtension != null) {
  8789. this._caps.vertexArrayObject = true;
  8790. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8791. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8792. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8793. }
  8794. else {
  8795. this._caps.vertexArrayObject = false;
  8796. }
  8797. }
  8798. // Instances count
  8799. if (this._webGLVersion > 1) {
  8800. this._caps.instancedArrays = true;
  8801. }
  8802. else {
  8803. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8804. if (instanceExtension != null) {
  8805. this._caps.instancedArrays = true;
  8806. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8807. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8808. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8809. }
  8810. else {
  8811. this._caps.instancedArrays = false;
  8812. }
  8813. }
  8814. // Intelligently add supported compressed formats in order to check for.
  8815. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8816. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8817. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8818. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8819. if (this._caps.astc)
  8820. this.texturesSupported.push('-astc.ktx');
  8821. if (this._caps.s3tc)
  8822. this.texturesSupported.push('-dxt.ktx');
  8823. if (this._caps.pvrtc)
  8824. this.texturesSupported.push('-pvrtc.ktx');
  8825. if (this._caps.etc2)
  8826. this.texturesSupported.push('-etc2.ktx');
  8827. if (this._caps.etc1)
  8828. this.texturesSupported.push('-etc1.ktx');
  8829. if (this._gl.getShaderPrecisionFormat) {
  8830. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8831. if (highp) {
  8832. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8833. }
  8834. }
  8835. // Depth buffer
  8836. this.setDepthBuffer(true);
  8837. this.setDepthFunctionToLessOrEqual();
  8838. this.setDepthWrite(true);
  8839. };
  8840. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8841. get: function () {
  8842. return this._webGLVersion;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8848. /**
  8849. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8850. */
  8851. get: function () {
  8852. return this._isStencilEnable;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Engine.prototype._prepareWorkingCanvas = function () {
  8858. if (this._workingCanvas) {
  8859. return;
  8860. }
  8861. this._workingCanvas = document.createElement("canvas");
  8862. var context = this._workingCanvas.getContext("2d");
  8863. if (context) {
  8864. this._workingContext = context;
  8865. }
  8866. };
  8867. Engine.prototype.resetTextureCache = function () {
  8868. for (var key in this._boundTexturesCache) {
  8869. this._boundTexturesCache[key] = null;
  8870. }
  8871. };
  8872. Engine.prototype.isDeterministicLockStep = function () {
  8873. return this._deterministicLockstep;
  8874. };
  8875. Engine.prototype.getLockstepMaxSteps = function () {
  8876. return this._lockstepMaxSteps;
  8877. };
  8878. Engine.prototype.getGlInfo = function () {
  8879. return {
  8880. vendor: this._glVendor,
  8881. renderer: this._glRenderer,
  8882. version: this._glVersion
  8883. };
  8884. };
  8885. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8886. if (useScreen === void 0) { useScreen = false; }
  8887. var viewport = camera.viewport;
  8888. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8889. };
  8890. Engine.prototype.getRenderWidth = function (useScreen) {
  8891. if (useScreen === void 0) { useScreen = false; }
  8892. if (!useScreen && this._currentRenderTarget) {
  8893. return this._currentRenderTarget.width;
  8894. }
  8895. return this._gl.drawingBufferWidth;
  8896. };
  8897. Engine.prototype.getRenderHeight = function (useScreen) {
  8898. if (useScreen === void 0) { useScreen = false; }
  8899. if (!useScreen && this._currentRenderTarget) {
  8900. return this._currentRenderTarget.height;
  8901. }
  8902. return this._gl.drawingBufferHeight;
  8903. };
  8904. Engine.prototype.getRenderingCanvas = function () {
  8905. return this._renderingCanvas;
  8906. };
  8907. Engine.prototype.getRenderingCanvasClientRect = function () {
  8908. if (!this._renderingCanvas) {
  8909. return null;
  8910. }
  8911. return this._renderingCanvas.getBoundingClientRect();
  8912. };
  8913. Engine.prototype.setHardwareScalingLevel = function (level) {
  8914. this._hardwareScalingLevel = level;
  8915. this.resize();
  8916. };
  8917. Engine.prototype.getHardwareScalingLevel = function () {
  8918. return this._hardwareScalingLevel;
  8919. };
  8920. Engine.prototype.getLoadedTexturesCache = function () {
  8921. return this._internalTexturesCache;
  8922. };
  8923. Engine.prototype.getCaps = function () {
  8924. return this._caps;
  8925. };
  8926. Object.defineProperty(Engine.prototype, "drawCalls", {
  8927. /** The number of draw calls submitted last frame */
  8928. get: function () {
  8929. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8930. return 0;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8936. get: function () {
  8937. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8938. return null;
  8939. },
  8940. enumerable: true,
  8941. configurable: true
  8942. });
  8943. Engine.prototype.getDepthFunction = function () {
  8944. return this._depthCullingState.depthFunc;
  8945. };
  8946. Engine.prototype.setDepthFunction = function (depthFunc) {
  8947. this._depthCullingState.depthFunc = depthFunc;
  8948. };
  8949. Engine.prototype.setDepthFunctionToGreater = function () {
  8950. this._depthCullingState.depthFunc = this._gl.GREATER;
  8951. };
  8952. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8953. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8954. };
  8955. Engine.prototype.setDepthFunctionToLess = function () {
  8956. this._depthCullingState.depthFunc = this._gl.LESS;
  8957. };
  8958. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8959. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8960. };
  8961. Engine.prototype.getStencilBuffer = function () {
  8962. return this._stencilState.stencilTest;
  8963. };
  8964. Engine.prototype.setStencilBuffer = function (enable) {
  8965. this._stencilState.stencilTest = enable;
  8966. };
  8967. Engine.prototype.getStencilMask = function () {
  8968. return this._stencilState.stencilMask;
  8969. };
  8970. Engine.prototype.setStencilMask = function (mask) {
  8971. this._stencilState.stencilMask = mask;
  8972. };
  8973. Engine.prototype.getStencilFunction = function () {
  8974. return this._stencilState.stencilFunc;
  8975. };
  8976. Engine.prototype.getStencilFunctionReference = function () {
  8977. return this._stencilState.stencilFuncRef;
  8978. };
  8979. Engine.prototype.getStencilFunctionMask = function () {
  8980. return this._stencilState.stencilFuncMask;
  8981. };
  8982. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8983. this._stencilState.stencilFunc = stencilFunc;
  8984. };
  8985. Engine.prototype.setStencilFunctionReference = function (reference) {
  8986. this._stencilState.stencilFuncRef = reference;
  8987. };
  8988. Engine.prototype.setStencilFunctionMask = function (mask) {
  8989. this._stencilState.stencilFuncMask = mask;
  8990. };
  8991. Engine.prototype.getStencilOperationFail = function () {
  8992. return this._stencilState.stencilOpStencilFail;
  8993. };
  8994. Engine.prototype.getStencilOperationDepthFail = function () {
  8995. return this._stencilState.stencilOpDepthFail;
  8996. };
  8997. Engine.prototype.getStencilOperationPass = function () {
  8998. return this._stencilState.stencilOpStencilDepthPass;
  8999. };
  9000. Engine.prototype.setStencilOperationFail = function (operation) {
  9001. this._stencilState.stencilOpStencilFail = operation;
  9002. };
  9003. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9004. this._stencilState.stencilOpDepthFail = operation;
  9005. };
  9006. Engine.prototype.setStencilOperationPass = function (operation) {
  9007. this._stencilState.stencilOpStencilDepthPass = operation;
  9008. };
  9009. Engine.prototype.setDitheringState = function (value) {
  9010. if (value) {
  9011. this._gl.enable(this._gl.DITHER);
  9012. }
  9013. else {
  9014. this._gl.disable(this._gl.DITHER);
  9015. }
  9016. };
  9017. Engine.prototype.setRasterizerState = function (value) {
  9018. if (value) {
  9019. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9020. }
  9021. else {
  9022. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9023. }
  9024. };
  9025. /**
  9026. * stop executing a render loop function and remove it from the execution array
  9027. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9028. */
  9029. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9030. if (!renderFunction) {
  9031. this._activeRenderLoops = [];
  9032. return;
  9033. }
  9034. var index = this._activeRenderLoops.indexOf(renderFunction);
  9035. if (index >= 0) {
  9036. this._activeRenderLoops.splice(index, 1);
  9037. }
  9038. };
  9039. Engine.prototype._renderLoop = function () {
  9040. if (!this._contextWasLost) {
  9041. var shouldRender = true;
  9042. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9043. shouldRender = false;
  9044. }
  9045. if (shouldRender) {
  9046. // Start new frame
  9047. this.beginFrame();
  9048. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9049. var renderFunction = this._activeRenderLoops[index];
  9050. renderFunction();
  9051. }
  9052. // Present
  9053. this.endFrame();
  9054. }
  9055. }
  9056. if (this._activeRenderLoops.length > 0) {
  9057. // Register new frame
  9058. var requester = null;
  9059. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9060. requester = this._vrDisplay;
  9061. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9062. }
  9063. else {
  9064. this._renderingQueueLaunched = false;
  9065. }
  9066. };
  9067. /**
  9068. * Register and execute a render loop. The engine can have more than one render function.
  9069. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9070. * @example
  9071. * engine.runRenderLoop(function () {
  9072. * scene.render()
  9073. * })
  9074. */
  9075. Engine.prototype.runRenderLoop = function (renderFunction) {
  9076. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9077. return;
  9078. }
  9079. this._activeRenderLoops.push(renderFunction);
  9080. if (!this._renderingQueueLaunched) {
  9081. this._renderingQueueLaunched = true;
  9082. this._bindedRenderFunction = this._renderLoop.bind(this);
  9083. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9084. }
  9085. };
  9086. /**
  9087. * Toggle full screen mode.
  9088. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9089. * @param {any} options - an options object to be sent to the requestFullscreen function
  9090. */
  9091. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9092. if (this.isFullscreen) {
  9093. BABYLON.Tools.ExitFullscreen();
  9094. }
  9095. else {
  9096. this._pointerLockRequested = requestPointerLock;
  9097. if (this._renderingCanvas) {
  9098. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9099. }
  9100. }
  9101. };
  9102. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9103. if (stencil === void 0) { stencil = false; }
  9104. this.applyStates();
  9105. var mode = 0;
  9106. if (backBuffer && color) {
  9107. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9108. mode |= this._gl.COLOR_BUFFER_BIT;
  9109. }
  9110. if (depth) {
  9111. this._gl.clearDepth(1.0);
  9112. mode |= this._gl.DEPTH_BUFFER_BIT;
  9113. }
  9114. if (stencil) {
  9115. this._gl.clearStencil(0);
  9116. mode |= this._gl.STENCIL_BUFFER_BIT;
  9117. }
  9118. this._gl.clear(mode);
  9119. };
  9120. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9121. var gl = this._gl;
  9122. // Save state
  9123. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9124. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9125. // Change state
  9126. gl.enable(gl.SCISSOR_TEST);
  9127. gl.scissor(x, y, width, height);
  9128. // Clear
  9129. this.clear(clearColor, true, true, true);
  9130. // Restore state
  9131. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9132. if (curScissor === true) {
  9133. gl.enable(gl.SCISSOR_TEST);
  9134. }
  9135. else {
  9136. gl.disable(gl.SCISSOR_TEST);
  9137. }
  9138. };
  9139. /**
  9140. * Set the WebGL's viewport
  9141. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9142. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9143. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9144. */
  9145. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9146. var width = requiredWidth || this.getRenderWidth();
  9147. var height = requiredHeight || this.getRenderHeight();
  9148. var x = viewport.x || 0;
  9149. var y = viewport.y || 0;
  9150. this._cachedViewport = viewport;
  9151. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9152. };
  9153. /**
  9154. * Directly set the WebGL Viewport
  9155. * The x, y, width & height are directly passed to the WebGL call
  9156. * @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.
  9157. */
  9158. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9159. var currentViewport = this._cachedViewport;
  9160. this._cachedViewport = null;
  9161. this._gl.viewport(x, y, width, height);
  9162. return currentViewport;
  9163. };
  9164. Engine.prototype.beginFrame = function () {
  9165. this.onBeginFrameObservable.notifyObservers(this);
  9166. this._measureFps();
  9167. };
  9168. Engine.prototype.endFrame = function () {
  9169. //force a flush in case we are using a bad OS.
  9170. if (this._badOS) {
  9171. this.flushFramebuffer();
  9172. }
  9173. //submit frame to the vr device, if enabled
  9174. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9175. // TODO: We should only submit the frame if we read frameData successfully.
  9176. this._vrDisplay.submitFrame();
  9177. }
  9178. this.onEndFrameObservable.notifyObservers(this);
  9179. };
  9180. /**
  9181. * resize the view according to the canvas' size.
  9182. * @example
  9183. * window.addEventListener("resize", function () {
  9184. * engine.resize();
  9185. * });
  9186. */
  9187. Engine.prototype.resize = function () {
  9188. // We're not resizing the size of the canvas while in VR mode & presenting
  9189. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9190. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9191. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9192. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9193. }
  9194. };
  9195. /**
  9196. * force a specific size of the canvas
  9197. * @param {number} width - the new canvas' width
  9198. * @param {number} height - the new canvas' height
  9199. */
  9200. Engine.prototype.setSize = function (width, height) {
  9201. if (!this._renderingCanvas) {
  9202. return;
  9203. }
  9204. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9205. return;
  9206. }
  9207. this._renderingCanvas.width = width;
  9208. this._renderingCanvas.height = height;
  9209. for (var index = 0; index < this.scenes.length; index++) {
  9210. var scene = this.scenes[index];
  9211. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9212. var cam = scene.cameras[camIndex];
  9213. cam._currentRenderId = 0;
  9214. }
  9215. }
  9216. if (this.onResizeObservable.hasObservers) {
  9217. this.onResizeObservable.notifyObservers(this);
  9218. }
  9219. };
  9220. // WebVR functions
  9221. Engine.prototype.isVRDevicePresent = function () {
  9222. return !!this._vrDisplay;
  9223. };
  9224. Engine.prototype.getVRDevice = function () {
  9225. return this._vrDisplay;
  9226. };
  9227. Engine.prototype.initWebVR = function () {
  9228. var _this = this;
  9229. var notifyObservers = function () {
  9230. var eventArgs = {
  9231. vrDisplay: _this._vrDisplay,
  9232. vrSupported: _this._vrSupported
  9233. };
  9234. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9235. };
  9236. if (!this._onVrDisplayConnect) {
  9237. this._onVrDisplayConnect = function (event) {
  9238. _this._vrDisplay = event.display;
  9239. notifyObservers();
  9240. };
  9241. this._onVrDisplayDisconnect = function () {
  9242. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9243. _this._vrDisplay = undefined;
  9244. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9245. notifyObservers();
  9246. };
  9247. this._onVrDisplayPresentChange = function () {
  9248. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9249. };
  9250. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9251. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9252. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9253. }
  9254. this._getVRDisplays(notifyObservers);
  9255. return this.onVRDisplayChangedObservable;
  9256. };
  9257. Engine.prototype.enableVR = function () {
  9258. var _this = this;
  9259. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9260. var onResolved = function () {
  9261. _this.onVRRequestPresentComplete.notifyObservers(true);
  9262. _this._onVRFullScreenTriggered();
  9263. };
  9264. var onRejected = function () {
  9265. _this.onVRRequestPresentComplete.notifyObservers(false);
  9266. };
  9267. this.onVRRequestPresentStart.notifyObservers(this);
  9268. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9269. }
  9270. };
  9271. Engine.prototype.disableVR = function () {
  9272. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9273. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9274. }
  9275. };
  9276. Engine.prototype._getVRDisplays = function (callback) {
  9277. var _this = this;
  9278. var getWebVRDevices = function (devices) {
  9279. _this._vrSupported = true;
  9280. // note that devices may actually be an empty array. This is fine;
  9281. // we expect this._vrDisplay to be undefined in this case.
  9282. return _this._vrDisplay = devices[0];
  9283. };
  9284. if (navigator.getVRDisplays) {
  9285. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9286. // TODO: System CANNOT support WebVR, despite API presence.
  9287. _this._vrSupported = false;
  9288. callback();
  9289. });
  9290. }
  9291. else {
  9292. // TODO: Browser does not support WebVR
  9293. this._vrDisplay = undefined;
  9294. this._vrSupported = false;
  9295. callback();
  9296. }
  9297. };
  9298. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9299. if (this._currentRenderTarget) {
  9300. this.unBindFramebuffer(this._currentRenderTarget);
  9301. }
  9302. this._currentRenderTarget = texture;
  9303. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9304. var gl = this._gl;
  9305. if (texture.isCube) {
  9306. if (faceIndex === undefined) {
  9307. faceIndex = 0;
  9308. }
  9309. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9310. }
  9311. if (this._cachedViewport && !forceFullscreenViewport) {
  9312. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9313. }
  9314. else {
  9315. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9316. }
  9317. this.wipeCaches();
  9318. };
  9319. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9320. if (this._currentFramebuffer !== framebuffer) {
  9321. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9322. this._currentFramebuffer = framebuffer;
  9323. }
  9324. };
  9325. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9326. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9327. this._currentRenderTarget = null;
  9328. // If MSAA, we need to bitblt back to main texture
  9329. var gl = this._gl;
  9330. if (texture._MSAAFramebuffer) {
  9331. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9332. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9333. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9334. }
  9335. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9336. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9337. gl.generateMipmap(gl.TEXTURE_2D);
  9338. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9339. }
  9340. if (onBeforeUnbind) {
  9341. if (texture._MSAAFramebuffer) {
  9342. // Bind the correct framebuffer
  9343. this.bindUnboundFramebuffer(texture._framebuffer);
  9344. }
  9345. onBeforeUnbind();
  9346. }
  9347. this.bindUnboundFramebuffer(null);
  9348. };
  9349. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9350. if (texture.generateMipMaps) {
  9351. var gl = this._gl;
  9352. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9353. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9354. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9355. }
  9356. };
  9357. Engine.prototype.flushFramebuffer = function () {
  9358. this._gl.flush();
  9359. };
  9360. Engine.prototype.restoreDefaultFramebuffer = function () {
  9361. if (this._currentRenderTarget) {
  9362. this.unBindFramebuffer(this._currentRenderTarget);
  9363. }
  9364. else {
  9365. this.bindUnboundFramebuffer(null);
  9366. }
  9367. if (this._cachedViewport) {
  9368. this.setViewport(this._cachedViewport);
  9369. }
  9370. this.wipeCaches();
  9371. };
  9372. // UBOs
  9373. Engine.prototype.createUniformBuffer = function (elements) {
  9374. var ubo = this._gl.createBuffer();
  9375. if (!ubo) {
  9376. throw new Error("Unable to create uniform buffer");
  9377. }
  9378. this.bindUniformBuffer(ubo);
  9379. if (elements instanceof Float32Array) {
  9380. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9381. }
  9382. else {
  9383. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9384. }
  9385. this.bindUniformBuffer(null);
  9386. ubo.references = 1;
  9387. return ubo;
  9388. };
  9389. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9390. var ubo = this._gl.createBuffer();
  9391. if (!ubo) {
  9392. throw new Error("Unable to create dynamic uniform buffer");
  9393. }
  9394. this.bindUniformBuffer(ubo);
  9395. if (elements instanceof Float32Array) {
  9396. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9397. }
  9398. else {
  9399. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9400. }
  9401. this.bindUniformBuffer(null);
  9402. ubo.references = 1;
  9403. return ubo;
  9404. };
  9405. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9406. this.bindUniformBuffer(uniformBuffer);
  9407. if (offset === undefined) {
  9408. offset = 0;
  9409. }
  9410. if (count === undefined) {
  9411. if (elements instanceof Float32Array) {
  9412. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9413. }
  9414. else {
  9415. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9416. }
  9417. }
  9418. else {
  9419. if (elements instanceof Float32Array) {
  9420. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9421. }
  9422. else {
  9423. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9424. }
  9425. }
  9426. this.bindUniformBuffer(null);
  9427. };
  9428. // VBOs
  9429. Engine.prototype._resetVertexBufferBinding = function () {
  9430. this.bindArrayBuffer(null);
  9431. this._cachedVertexBuffers = null;
  9432. };
  9433. Engine.prototype.createVertexBuffer = function (vertices) {
  9434. var vbo = this._gl.createBuffer();
  9435. if (!vbo) {
  9436. throw new Error("Unable to create vertex buffer");
  9437. }
  9438. this.bindArrayBuffer(vbo);
  9439. if (vertices instanceof Float32Array) {
  9440. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9441. }
  9442. else {
  9443. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9444. }
  9445. this._resetVertexBufferBinding();
  9446. vbo.references = 1;
  9447. return vbo;
  9448. };
  9449. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9450. var vbo = this._gl.createBuffer();
  9451. if (!vbo) {
  9452. throw new Error("Unable to create dynamic vertex buffer");
  9453. }
  9454. this.bindArrayBuffer(vbo);
  9455. if (vertices instanceof Float32Array) {
  9456. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9457. }
  9458. else {
  9459. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9460. }
  9461. this._resetVertexBufferBinding();
  9462. vbo.references = 1;
  9463. return vbo;
  9464. };
  9465. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9466. if (offset === void 0) { offset = 0; }
  9467. // Force cache update
  9468. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9469. this.bindIndexBuffer(indexBuffer);
  9470. var arrayBuffer;
  9471. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9472. arrayBuffer = indices;
  9473. }
  9474. else {
  9475. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9476. }
  9477. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9478. this._resetIndexBufferBinding();
  9479. };
  9480. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9481. this.bindArrayBuffer(vertexBuffer);
  9482. if (offset === undefined) {
  9483. offset = 0;
  9484. }
  9485. if (count === undefined) {
  9486. if (vertices instanceof Float32Array) {
  9487. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9488. }
  9489. else {
  9490. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9491. }
  9492. }
  9493. else {
  9494. if (vertices instanceof Float32Array) {
  9495. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9496. }
  9497. else {
  9498. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9499. }
  9500. }
  9501. this._resetVertexBufferBinding();
  9502. };
  9503. Engine.prototype._resetIndexBufferBinding = function () {
  9504. this.bindIndexBuffer(null);
  9505. this._cachedIndexBuffer = null;
  9506. };
  9507. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9508. var vbo = this._gl.createBuffer();
  9509. if (!vbo) {
  9510. throw new Error("Unable to create index buffer");
  9511. }
  9512. this.bindIndexBuffer(vbo);
  9513. // Check for 32 bits indices
  9514. var arrayBuffer;
  9515. var need32Bits = false;
  9516. if (indices instanceof Uint16Array) {
  9517. arrayBuffer = indices;
  9518. }
  9519. else {
  9520. //check 32 bit support
  9521. if (this._caps.uintIndices) {
  9522. if (indices instanceof Uint32Array) {
  9523. arrayBuffer = indices;
  9524. need32Bits = true;
  9525. }
  9526. else {
  9527. //number[] or Int32Array, check if 32 bit is necessary
  9528. for (var index = 0; index < indices.length; index++) {
  9529. if (indices[index] > 65535) {
  9530. need32Bits = true;
  9531. break;
  9532. }
  9533. }
  9534. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9535. }
  9536. }
  9537. else {
  9538. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9539. arrayBuffer = new Uint16Array(indices);
  9540. }
  9541. }
  9542. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9543. this._resetIndexBufferBinding();
  9544. vbo.references = 1;
  9545. vbo.is32Bits = need32Bits;
  9546. return vbo;
  9547. };
  9548. Engine.prototype.bindArrayBuffer = function (buffer) {
  9549. if (!this._vaoRecordInProgress) {
  9550. this._unbindVertexArrayObject();
  9551. }
  9552. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9553. };
  9554. Engine.prototype.bindUniformBuffer = function (buffer) {
  9555. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9556. };
  9557. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9558. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9559. };
  9560. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9561. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9562. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9563. };
  9564. ;
  9565. Engine.prototype.bindIndexBuffer = function (buffer) {
  9566. if (!this._vaoRecordInProgress) {
  9567. this._unbindVertexArrayObject();
  9568. }
  9569. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9570. };
  9571. Engine.prototype.bindBuffer = function (buffer, target) {
  9572. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9573. this._gl.bindBuffer(target, buffer);
  9574. this._currentBoundBuffer[target] = buffer;
  9575. }
  9576. };
  9577. Engine.prototype.updateArrayBuffer = function (data) {
  9578. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9579. };
  9580. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9581. var pointer = this._currentBufferPointers[indx];
  9582. var changed = false;
  9583. if (!pointer.active) {
  9584. changed = true;
  9585. pointer.active = true;
  9586. pointer.index = indx;
  9587. pointer.size = size;
  9588. pointer.type = type;
  9589. pointer.normalized = normalized;
  9590. pointer.stride = stride;
  9591. pointer.offset = offset;
  9592. pointer.buffer = buffer;
  9593. }
  9594. else {
  9595. if (pointer.buffer !== buffer) {
  9596. pointer.buffer = buffer;
  9597. changed = true;
  9598. }
  9599. if (pointer.size !== size) {
  9600. pointer.size = size;
  9601. changed = true;
  9602. }
  9603. if (pointer.type !== type) {
  9604. pointer.type = type;
  9605. changed = true;
  9606. }
  9607. if (pointer.normalized !== normalized) {
  9608. pointer.normalized = normalized;
  9609. changed = true;
  9610. }
  9611. if (pointer.stride !== stride) {
  9612. pointer.stride = stride;
  9613. changed = true;
  9614. }
  9615. if (pointer.offset !== offset) {
  9616. pointer.offset = offset;
  9617. changed = true;
  9618. }
  9619. }
  9620. if (changed || this._vaoRecordInProgress) {
  9621. this.bindArrayBuffer(buffer);
  9622. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9623. }
  9624. };
  9625. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9626. if (indexBuffer == null) {
  9627. return;
  9628. }
  9629. if (this._cachedIndexBuffer !== indexBuffer) {
  9630. this._cachedIndexBuffer = indexBuffer;
  9631. this.bindIndexBuffer(indexBuffer);
  9632. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9633. }
  9634. };
  9635. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9636. var attributes = effect.getAttributesNames();
  9637. if (!this._vaoRecordInProgress) {
  9638. this._unbindVertexArrayObject();
  9639. }
  9640. this.unbindAllAttributes();
  9641. for (var index = 0; index < attributes.length; index++) {
  9642. var order = effect.getAttributeLocation(index);
  9643. if (order >= 0) {
  9644. var vertexBuffer = vertexBuffers[attributes[index]];
  9645. if (!vertexBuffer) {
  9646. continue;
  9647. }
  9648. this._gl.enableVertexAttribArray(order);
  9649. if (!this._vaoRecordInProgress) {
  9650. this._vertexAttribArraysEnabled[order] = true;
  9651. }
  9652. var buffer = vertexBuffer.getBuffer();
  9653. if (buffer) {
  9654. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9655. if (vertexBuffer.getIsInstanced()) {
  9656. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9657. if (!this._vaoRecordInProgress) {
  9658. this._currentInstanceLocations.push(order);
  9659. this._currentInstanceBuffers.push(buffer);
  9660. }
  9661. }
  9662. }
  9663. }
  9664. }
  9665. };
  9666. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9667. var vao = this._gl.createVertexArray();
  9668. this._vaoRecordInProgress = true;
  9669. this._gl.bindVertexArray(vao);
  9670. this._mustWipeVertexAttributes = true;
  9671. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9672. this.bindIndexBuffer(indexBuffer);
  9673. this._vaoRecordInProgress = false;
  9674. this._gl.bindVertexArray(null);
  9675. return vao;
  9676. };
  9677. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9678. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9679. this._cachedVertexArrayObject = vertexArrayObject;
  9680. this._gl.bindVertexArray(vertexArrayObject);
  9681. this._cachedVertexBuffers = null;
  9682. this._cachedIndexBuffer = null;
  9683. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9684. this._mustWipeVertexAttributes = true;
  9685. }
  9686. };
  9687. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9688. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9689. this._cachedVertexBuffers = vertexBuffer;
  9690. this._cachedEffectForVertexBuffers = effect;
  9691. var attributesCount = effect.getAttributesCount();
  9692. this._unbindVertexArrayObject();
  9693. this.unbindAllAttributes();
  9694. var offset = 0;
  9695. for (var index = 0; index < attributesCount; index++) {
  9696. if (index < vertexDeclaration.length) {
  9697. var order = effect.getAttributeLocation(index);
  9698. if (order >= 0) {
  9699. this._gl.enableVertexAttribArray(order);
  9700. this._vertexAttribArraysEnabled[order] = true;
  9701. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9702. }
  9703. offset += vertexDeclaration[index] * 4;
  9704. }
  9705. }
  9706. }
  9707. this._bindIndexBufferWithCache(indexBuffer);
  9708. };
  9709. Engine.prototype._unbindVertexArrayObject = function () {
  9710. if (!this._cachedVertexArrayObject) {
  9711. return;
  9712. }
  9713. this._cachedVertexArrayObject = null;
  9714. this._gl.bindVertexArray(null);
  9715. };
  9716. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9717. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9718. this._cachedVertexBuffers = vertexBuffers;
  9719. this._cachedEffectForVertexBuffers = effect;
  9720. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9721. }
  9722. this._bindIndexBufferWithCache(indexBuffer);
  9723. };
  9724. Engine.prototype.unbindInstanceAttributes = function () {
  9725. var boundBuffer;
  9726. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9727. var instancesBuffer = this._currentInstanceBuffers[i];
  9728. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9729. boundBuffer = instancesBuffer;
  9730. this.bindArrayBuffer(instancesBuffer);
  9731. }
  9732. var offsetLocation = this._currentInstanceLocations[i];
  9733. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9734. }
  9735. this._currentInstanceBuffers.length = 0;
  9736. this._currentInstanceLocations.length = 0;
  9737. };
  9738. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9739. this._gl.deleteVertexArray(vao);
  9740. };
  9741. Engine.prototype._releaseBuffer = function (buffer) {
  9742. buffer.references--;
  9743. if (buffer.references === 0) {
  9744. this._gl.deleteBuffer(buffer);
  9745. return true;
  9746. }
  9747. return false;
  9748. };
  9749. Engine.prototype.createInstancesBuffer = function (capacity) {
  9750. var buffer = this._gl.createBuffer();
  9751. if (!buffer) {
  9752. throw new Error("Unable to create instance buffer");
  9753. }
  9754. buffer.capacity = capacity;
  9755. this.bindArrayBuffer(buffer);
  9756. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9757. return buffer;
  9758. };
  9759. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9760. this._gl.deleteBuffer(buffer);
  9761. };
  9762. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9763. this.bindArrayBuffer(instancesBuffer);
  9764. if (data) {
  9765. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9766. }
  9767. if (offsetLocations[0].index !== undefined) {
  9768. var stride = 0;
  9769. for (var i = 0; i < offsetLocations.length; i++) {
  9770. var ai = offsetLocations[i];
  9771. stride += ai.attributeSize * 4;
  9772. }
  9773. for (var i = 0; i < offsetLocations.length; i++) {
  9774. var ai = offsetLocations[i];
  9775. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9776. this._gl.enableVertexAttribArray(ai.index);
  9777. this._vertexAttribArraysEnabled[ai.index] = true;
  9778. }
  9779. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9780. this._gl.vertexAttribDivisor(ai.index, 1);
  9781. this._currentInstanceLocations.push(ai.index);
  9782. this._currentInstanceBuffers.push(instancesBuffer);
  9783. }
  9784. }
  9785. else {
  9786. for (var index = 0; index < 4; index++) {
  9787. var offsetLocation = offsetLocations[index];
  9788. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9789. this._gl.enableVertexAttribArray(offsetLocation);
  9790. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9791. }
  9792. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9793. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9794. this._currentInstanceLocations.push(offsetLocation);
  9795. this._currentInstanceBuffers.push(instancesBuffer);
  9796. }
  9797. }
  9798. };
  9799. Engine.prototype.applyStates = function () {
  9800. this._depthCullingState.apply(this._gl);
  9801. this._stencilState.apply(this._gl);
  9802. this._alphaState.apply(this._gl);
  9803. };
  9804. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9805. // Apply states
  9806. this.applyStates();
  9807. this._drawCalls.addCount(1, false);
  9808. // Render
  9809. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9810. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9811. if (instancesCount) {
  9812. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9813. return;
  9814. }
  9815. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9816. };
  9817. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9818. // Apply states
  9819. this.applyStates();
  9820. this._drawCalls.addCount(1, false);
  9821. if (instancesCount) {
  9822. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9823. return;
  9824. }
  9825. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9826. };
  9827. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9828. // Apply states
  9829. this.applyStates();
  9830. this._drawCalls.addCount(1, false);
  9831. if (instancesCount) {
  9832. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9833. return;
  9834. }
  9835. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9836. };
  9837. // Shaders
  9838. Engine.prototype._releaseEffect = function (effect) {
  9839. if (this._compiledEffects[effect._key]) {
  9840. delete this._compiledEffects[effect._key];
  9841. this._deleteProgram(effect.getProgram());
  9842. }
  9843. };
  9844. Engine.prototype._deleteProgram = function (program) {
  9845. if (program) {
  9846. program.__SPECTOR_rebuildProgram = null;
  9847. if (program.transformFeedback) {
  9848. this.deleteTransformFeedback(program.transformFeedback);
  9849. program.transformFeedback = null;
  9850. }
  9851. this._gl.deleteProgram(program);
  9852. }
  9853. };
  9854. /**
  9855. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9856. * @param samplers An array of string used to represent textures
  9857. */
  9858. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9859. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9860. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9861. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9862. if (this._compiledEffects[name]) {
  9863. var compiledEffect = this._compiledEffects[name];
  9864. if (onCompiled && compiledEffect.isReady()) {
  9865. onCompiled(compiledEffect);
  9866. }
  9867. return compiledEffect;
  9868. }
  9869. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9870. effect._key = name;
  9871. this._compiledEffects[name] = effect;
  9872. return effect;
  9873. };
  9874. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9875. if (uniformsNames === void 0) { uniformsNames = []; }
  9876. if (samplers === void 0) { samplers = []; }
  9877. if (defines === void 0) { defines = ""; }
  9878. return this.createEffect({
  9879. vertex: "particles",
  9880. fragmentElement: fragmentName
  9881. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9882. };
  9883. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9884. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9885. context = context || this._gl;
  9886. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9887. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9888. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9889. };
  9890. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9891. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9892. context = context || this._gl;
  9893. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9894. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9895. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9896. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9897. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9898. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9899. return program;
  9900. };
  9901. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9902. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9903. var shaderProgram = context.createProgram();
  9904. if (!shaderProgram) {
  9905. throw new Error("Unable to create program");
  9906. }
  9907. context.attachShader(shaderProgram, vertexShader);
  9908. context.attachShader(shaderProgram, fragmentShader);
  9909. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9910. var transformFeedback = this.createTransformFeedback();
  9911. this.bindTransformFeedback(transformFeedback);
  9912. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9913. shaderProgram.transformFeedback = transformFeedback;
  9914. }
  9915. context.linkProgram(shaderProgram);
  9916. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9917. this.bindTransformFeedback(null);
  9918. }
  9919. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9920. if (!linked) {
  9921. context.validateProgram(shaderProgram);
  9922. var error = context.getProgramInfoLog(shaderProgram);
  9923. if (error) {
  9924. throw new Error(error);
  9925. }
  9926. }
  9927. context.deleteShader(vertexShader);
  9928. context.deleteShader(fragmentShader);
  9929. return shaderProgram;
  9930. };
  9931. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9932. var results = new Array();
  9933. for (var index = 0; index < uniformsNames.length; index++) {
  9934. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9935. }
  9936. return results;
  9937. };
  9938. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9939. var results = [];
  9940. for (var index = 0; index < attributesNames.length; index++) {
  9941. try {
  9942. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9943. }
  9944. catch (e) {
  9945. results.push(-1);
  9946. }
  9947. }
  9948. return results;
  9949. };
  9950. Engine.prototype.enableEffect = function (effect) {
  9951. if (!effect) {
  9952. return;
  9953. }
  9954. // Use program
  9955. this.setProgram(effect.getProgram());
  9956. this._currentEffect = effect;
  9957. if (effect.onBind) {
  9958. effect.onBind(effect);
  9959. }
  9960. effect.onBindObservable.notifyObservers(effect);
  9961. };
  9962. Engine.prototype.setIntArray = function (uniform, array) {
  9963. if (!uniform)
  9964. return;
  9965. this._gl.uniform1iv(uniform, array);
  9966. };
  9967. Engine.prototype.setIntArray2 = function (uniform, array) {
  9968. if (!uniform || array.length % 2 !== 0)
  9969. return;
  9970. this._gl.uniform2iv(uniform, array);
  9971. };
  9972. Engine.prototype.setIntArray3 = function (uniform, array) {
  9973. if (!uniform || array.length % 3 !== 0)
  9974. return;
  9975. this._gl.uniform3iv(uniform, array);
  9976. };
  9977. Engine.prototype.setIntArray4 = function (uniform, array) {
  9978. if (!uniform || array.length % 4 !== 0)
  9979. return;
  9980. this._gl.uniform4iv(uniform, array);
  9981. };
  9982. Engine.prototype.setFloatArray = function (uniform, array) {
  9983. if (!uniform)
  9984. return;
  9985. this._gl.uniform1fv(uniform, array);
  9986. };
  9987. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9988. if (!uniform || array.length % 2 !== 0)
  9989. return;
  9990. this._gl.uniform2fv(uniform, array);
  9991. };
  9992. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9993. if (!uniform || array.length % 3 !== 0)
  9994. return;
  9995. this._gl.uniform3fv(uniform, array);
  9996. };
  9997. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9998. if (!uniform || array.length % 4 !== 0)
  9999. return;
  10000. this._gl.uniform4fv(uniform, array);
  10001. };
  10002. Engine.prototype.setArray = function (uniform, array) {
  10003. if (!uniform)
  10004. return;
  10005. this._gl.uniform1fv(uniform, array);
  10006. };
  10007. Engine.prototype.setArray2 = function (uniform, array) {
  10008. if (!uniform || array.length % 2 !== 0)
  10009. return;
  10010. this._gl.uniform2fv(uniform, array);
  10011. };
  10012. Engine.prototype.setArray3 = function (uniform, array) {
  10013. if (!uniform || array.length % 3 !== 0)
  10014. return;
  10015. this._gl.uniform3fv(uniform, array);
  10016. };
  10017. Engine.prototype.setArray4 = function (uniform, array) {
  10018. if (!uniform || array.length % 4 !== 0)
  10019. return;
  10020. this._gl.uniform4fv(uniform, array);
  10021. };
  10022. Engine.prototype.setMatrices = function (uniform, matrices) {
  10023. if (!uniform)
  10024. return;
  10025. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10026. };
  10027. Engine.prototype.setMatrix = function (uniform, matrix) {
  10028. if (!uniform)
  10029. return;
  10030. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10031. };
  10032. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10033. if (!uniform)
  10034. return;
  10035. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10036. };
  10037. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10038. if (!uniform)
  10039. return;
  10040. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10041. };
  10042. Engine.prototype.setFloat = function (uniform, value) {
  10043. if (!uniform)
  10044. return;
  10045. this._gl.uniform1f(uniform, value);
  10046. };
  10047. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10048. if (!uniform)
  10049. return;
  10050. this._gl.uniform2f(uniform, x, y);
  10051. };
  10052. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10053. if (!uniform)
  10054. return;
  10055. this._gl.uniform3f(uniform, x, y, z);
  10056. };
  10057. Engine.prototype.setBool = function (uniform, bool) {
  10058. if (!uniform)
  10059. return;
  10060. this._gl.uniform1i(uniform, bool);
  10061. };
  10062. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10063. if (!uniform)
  10064. return;
  10065. this._gl.uniform4f(uniform, x, y, z, w);
  10066. };
  10067. Engine.prototype.setColor3 = function (uniform, color3) {
  10068. if (!uniform)
  10069. return;
  10070. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10071. };
  10072. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10073. if (!uniform)
  10074. return;
  10075. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10076. };
  10077. // States
  10078. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10079. if (zOffset === void 0) { zOffset = 0; }
  10080. if (reverseSide === void 0) { reverseSide = false; }
  10081. // Culling
  10082. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10083. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10084. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10085. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10086. if (culling) {
  10087. this._depthCullingState.cullFace = cullFace;
  10088. this._depthCullingState.cull = true;
  10089. }
  10090. else {
  10091. this._depthCullingState.cull = false;
  10092. }
  10093. }
  10094. // Z offset
  10095. this.setZOffset(zOffset);
  10096. };
  10097. Engine.prototype.setZOffset = function (value) {
  10098. this._depthCullingState.zOffset = value;
  10099. };
  10100. Engine.prototype.getZOffset = function () {
  10101. return this._depthCullingState.zOffset;
  10102. };
  10103. Engine.prototype.setDepthBuffer = function (enable) {
  10104. this._depthCullingState.depthTest = enable;
  10105. };
  10106. Engine.prototype.getDepthWrite = function () {
  10107. return this._depthCullingState.depthMask;
  10108. };
  10109. Engine.prototype.setDepthWrite = function (enable) {
  10110. this._depthCullingState.depthMask = enable;
  10111. };
  10112. Engine.prototype.setColorWrite = function (enable) {
  10113. this._gl.colorMask(enable, enable, enable, enable);
  10114. this._colorWrite = enable;
  10115. };
  10116. Engine.prototype.getColorWrite = function () {
  10117. return this._colorWrite;
  10118. };
  10119. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10120. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10121. };
  10122. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10123. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10124. if (this._alphaMode === mode) {
  10125. return;
  10126. }
  10127. switch (mode) {
  10128. case Engine.ALPHA_DISABLE:
  10129. this._alphaState.alphaBlend = false;
  10130. break;
  10131. case Engine.ALPHA_PREMULTIPLIED:
  10132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10133. this._alphaState.alphaBlend = true;
  10134. break;
  10135. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10137. this._alphaState.alphaBlend = true;
  10138. break;
  10139. case Engine.ALPHA_COMBINE:
  10140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10141. this._alphaState.alphaBlend = true;
  10142. break;
  10143. case Engine.ALPHA_ONEONE:
  10144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10145. this._alphaState.alphaBlend = true;
  10146. break;
  10147. case Engine.ALPHA_ADD:
  10148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10149. this._alphaState.alphaBlend = true;
  10150. break;
  10151. case Engine.ALPHA_SUBTRACT:
  10152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10153. this._alphaState.alphaBlend = true;
  10154. break;
  10155. case Engine.ALPHA_MULTIPLY:
  10156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10157. this._alphaState.alphaBlend = true;
  10158. break;
  10159. case Engine.ALPHA_MAXIMIZED:
  10160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10161. this._alphaState.alphaBlend = true;
  10162. break;
  10163. case Engine.ALPHA_INTERPOLATE:
  10164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10165. this._alphaState.alphaBlend = true;
  10166. break;
  10167. case Engine.ALPHA_SCREENMODE:
  10168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10169. this._alphaState.alphaBlend = true;
  10170. break;
  10171. }
  10172. if (!noDepthWriteChange) {
  10173. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10174. }
  10175. this._alphaMode = mode;
  10176. };
  10177. Engine.prototype.getAlphaMode = function () {
  10178. return this._alphaMode;
  10179. };
  10180. Engine.prototype.setAlphaTesting = function (enable) {
  10181. this._alphaTest = enable;
  10182. };
  10183. Engine.prototype.getAlphaTesting = function () {
  10184. return !!this._alphaTest;
  10185. };
  10186. // Textures
  10187. Engine.prototype.wipeCaches = function (bruteForce) {
  10188. if (this.preventCacheWipeBetweenFrames) {
  10189. return;
  10190. }
  10191. this.resetTextureCache();
  10192. this._currentEffect = null;
  10193. // 6/8/2017: deltakosh: Should not be required anymore.
  10194. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10195. if (bruteForce) {
  10196. this._currentProgram = null;
  10197. this._stencilState.reset();
  10198. this._depthCullingState.reset();
  10199. this.setDepthFunctionToLessOrEqual();
  10200. this._alphaState.reset();
  10201. }
  10202. this._cachedVertexBuffers = null;
  10203. this._cachedIndexBuffer = null;
  10204. this._cachedEffectForVertexBuffers = null;
  10205. this._unbindVertexArrayObject();
  10206. this.bindIndexBuffer(null);
  10207. this.bindArrayBuffer(null);
  10208. };
  10209. /**
  10210. * Set the compressed texture format to use, based on the formats you have, and the formats
  10211. * supported by the hardware / browser.
  10212. *
  10213. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10214. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10215. * to API arguments needed to compressed textures. This puts the burden on the container
  10216. * generator to house the arcane code for determining these for current & future formats.
  10217. *
  10218. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10219. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10220. *
  10221. * Note: The result of this call is not taken into account when a texture is base64.
  10222. *
  10223. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10224. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10225. *
  10226. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10227. * @returns The extension selected.
  10228. */
  10229. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10230. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10231. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10232. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10233. return this._textureFormatInUse = this._texturesSupported[i];
  10234. }
  10235. }
  10236. }
  10237. // actively set format to nothing, to allow this to be called more than once
  10238. // and possibly fail the 2nd time
  10239. this._textureFormatInUse = null;
  10240. return null;
  10241. };
  10242. Engine.prototype._createTexture = function () {
  10243. var texture = this._gl.createTexture();
  10244. if (!texture) {
  10245. throw new Error("Unable to create texture");
  10246. }
  10247. return texture;
  10248. };
  10249. /**
  10250. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10251. * @param {string} urlArg- This contains one of the following:
  10252. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10253. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10254. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10255. *
  10256. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10257. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10258. * @param {Scene} scene- Needed for loading to the correct scene.
  10259. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10260. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10261. * @param {callback} onError- Optional callback to be called upon failure.
  10262. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10263. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10264. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10265. *
  10266. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10267. */
  10268. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10269. var _this = this;
  10270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10271. if (onLoad === void 0) { onLoad = null; }
  10272. if (onError === void 0) { onError = null; }
  10273. if (buffer === void 0) { buffer = null; }
  10274. if (fallBack === void 0) { fallBack = null; }
  10275. if (format === void 0) { format = null; }
  10276. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10277. var fromData = url.substr(0, 5) === "data:";
  10278. var fromBlob = url.substr(0, 5) === "blob:";
  10279. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10280. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10281. // establish the file extension, if possible
  10282. var lastDot = url.lastIndexOf('.');
  10283. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10284. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10285. var isTGA = (extension === ".tga");
  10286. // determine if a ktx file should be substituted
  10287. var isKTX = false;
  10288. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10289. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10290. isKTX = true;
  10291. }
  10292. if (scene) {
  10293. scene._addPendingData(texture);
  10294. }
  10295. texture.url = url;
  10296. texture.generateMipMaps = !noMipmap;
  10297. texture.samplingMode = samplingMode;
  10298. texture.invertY = invertY;
  10299. if (!this._doNotHandleContextLost) {
  10300. // Keep a link to the buffer only if we plan to handle context lost
  10301. texture._buffer = buffer;
  10302. }
  10303. var onLoadObserver = null;
  10304. if (onLoad && !fallBack) {
  10305. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10306. }
  10307. if (!fallBack)
  10308. this._internalTexturesCache.push(texture);
  10309. var onerror = function (message, exception) {
  10310. if (scene) {
  10311. scene._removePendingData(texture);
  10312. }
  10313. if (onLoadObserver) {
  10314. texture.onLoadedObservable.remove(onLoadObserver);
  10315. }
  10316. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10317. if (isKTX) {
  10318. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10319. }
  10320. else if (BABYLON.Tools.UseFallbackTexture) {
  10321. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10322. }
  10323. if (onError) {
  10324. onError(message || "Unknown error", exception);
  10325. }
  10326. };
  10327. var callback = null;
  10328. // processing for non-image formats
  10329. if (isKTX || isTGA || isDDS) {
  10330. if (isKTX) {
  10331. callback = function (data) {
  10332. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10333. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10334. ktx.uploadLevels(_this._gl, !noMipmap);
  10335. return false;
  10336. }, samplingMode);
  10337. };
  10338. }
  10339. else if (isTGA) {
  10340. callback = function (arrayBuffer) {
  10341. var data = new Uint8Array(arrayBuffer);
  10342. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10343. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10344. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10345. return false;
  10346. }, samplingMode);
  10347. };
  10348. }
  10349. else if (isDDS) {
  10350. callback = function (data) {
  10351. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10352. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10353. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10354. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10355. return false;
  10356. }, samplingMode);
  10357. };
  10358. }
  10359. if (!buffer) {
  10360. BABYLON.Tools.LoadFile(url, function (data) {
  10361. if (callback) {
  10362. callback(data);
  10363. }
  10364. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10365. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10366. });
  10367. }
  10368. else {
  10369. if (callback) {
  10370. callback(buffer);
  10371. }
  10372. }
  10373. // image format processing
  10374. }
  10375. else {
  10376. var onload = function (img) {
  10377. if (fromBlob && !_this._doNotHandleContextLost) {
  10378. // We need to store the image if we need to rebuild the texture
  10379. // in case of a webgl context lost
  10380. texture._buffer = img;
  10381. }
  10382. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10383. var gl = _this._gl;
  10384. var isPot = (img.width === potWidth && img.height === potHeight);
  10385. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10386. if (isPot) {
  10387. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10388. return false;
  10389. }
  10390. // Using shaders to rescale because canvas.drawImage is lossy
  10391. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10392. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10393. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10398. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10399. _this._releaseTexture(source);
  10400. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10401. continuationCallback();
  10402. });
  10403. return true;
  10404. }, samplingMode);
  10405. };
  10406. if (!fromData || isBase64)
  10407. if (buffer instanceof HTMLImageElement) {
  10408. onload(buffer);
  10409. }
  10410. else {
  10411. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10412. }
  10413. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10414. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10415. else
  10416. onload(buffer);
  10417. }
  10418. return texture;
  10419. };
  10420. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10421. var _this = this;
  10422. var rtt = this.createRenderTargetTexture({
  10423. width: destination.width,
  10424. height: destination.height,
  10425. }, {
  10426. generateMipMaps: false,
  10427. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10428. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10429. generateDepthBuffer: false,
  10430. generateStencilBuffer: false
  10431. });
  10432. if (!this._rescalePostProcess) {
  10433. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10434. }
  10435. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10436. _this._rescalePostProcess.onApply = function (effect) {
  10437. effect._bindTexture("textureSampler", source);
  10438. };
  10439. var hostingScene = scene;
  10440. if (!hostingScene) {
  10441. hostingScene = _this.scenes[_this.scenes.length - 1];
  10442. }
  10443. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10444. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10445. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10446. _this.unBindFramebuffer(rtt);
  10447. _this._releaseTexture(rtt);
  10448. if (onComplete) {
  10449. onComplete();
  10450. }
  10451. });
  10452. };
  10453. Engine.prototype._getInternalFormat = function (format) {
  10454. var internalFormat = this._gl.RGBA;
  10455. switch (format) {
  10456. case Engine.TEXTUREFORMAT_ALPHA:
  10457. internalFormat = this._gl.ALPHA;
  10458. break;
  10459. case Engine.TEXTUREFORMAT_LUMINANCE:
  10460. internalFormat = this._gl.LUMINANCE;
  10461. break;
  10462. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10463. internalFormat = this._gl.LUMINANCE_ALPHA;
  10464. break;
  10465. case Engine.TEXTUREFORMAT_RGB:
  10466. internalFormat = this._gl.RGB;
  10467. break;
  10468. case Engine.TEXTUREFORMAT_RGBA:
  10469. internalFormat = this._gl.RGBA;
  10470. break;
  10471. }
  10472. return internalFormat;
  10473. };
  10474. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10475. if (compression === void 0) { compression = null; }
  10476. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10477. if (!texture) {
  10478. return;
  10479. }
  10480. var internalFormat = this._getInternalFormat(format);
  10481. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10482. var textureType = this._getWebGLTextureType(type);
  10483. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10484. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10485. if (!this._doNotHandleContextLost) {
  10486. texture._bufferView = data;
  10487. texture.format = format;
  10488. texture.type = type;
  10489. texture.invertY = invertY;
  10490. texture._compression = compression;
  10491. }
  10492. if (texture.width % 4 !== 0) {
  10493. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10494. }
  10495. if (compression && data) {
  10496. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10497. }
  10498. else {
  10499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10500. }
  10501. if (texture.generateMipMaps) {
  10502. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10503. }
  10504. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10505. this.resetTextureCache();
  10506. texture.isReady = true;
  10507. };
  10508. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10509. if (compression === void 0) { compression = null; }
  10510. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  10511. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10512. texture.baseWidth = width;
  10513. texture.baseHeight = height;
  10514. texture.width = width;
  10515. texture.height = height;
  10516. texture.format = format;
  10517. texture.generateMipMaps = generateMipMaps;
  10518. texture.samplingMode = samplingMode;
  10519. texture.invertY = invertY;
  10520. texture._compression = compression;
  10521. texture.type = type;
  10522. if (!this._doNotHandleContextLost) {
  10523. texture._bufferView = data;
  10524. }
  10525. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10527. // Filters
  10528. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10531. if (generateMipMaps) {
  10532. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10533. }
  10534. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10535. this._internalTexturesCache.push(texture);
  10536. return texture;
  10537. };
  10538. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10539. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10540. texture.baseWidth = width;
  10541. texture.baseHeight = height;
  10542. if (generateMipMaps) {
  10543. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10544. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10545. }
  10546. this.resetTextureCache();
  10547. texture.width = width;
  10548. texture.height = height;
  10549. texture.isReady = false;
  10550. texture.generateMipMaps = generateMipMaps;
  10551. texture.samplingMode = samplingMode;
  10552. this.updateTextureSamplingMode(samplingMode, texture);
  10553. this._internalTexturesCache.push(texture);
  10554. return texture;
  10555. };
  10556. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10557. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10558. if (texture.isCube) {
  10559. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10560. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10561. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10562. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10563. }
  10564. else if (texture.is3D) {
  10565. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10566. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10567. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10568. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10569. }
  10570. else {
  10571. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10572. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10573. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10574. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10575. }
  10576. texture.samplingMode = samplingMode;
  10577. };
  10578. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10579. if (premulAlpha === void 0) { premulAlpha = false; }
  10580. if (!texture) {
  10581. return;
  10582. }
  10583. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10584. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10585. if (premulAlpha) {
  10586. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10587. }
  10588. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10589. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10590. if (texture.generateMipMaps) {
  10591. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10592. }
  10593. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10594. if (premulAlpha) {
  10595. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10596. }
  10597. this.resetTextureCache();
  10598. texture.isReady = true;
  10599. };
  10600. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10601. if (!texture || texture._isDisabled) {
  10602. return;
  10603. }
  10604. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10605. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10606. try {
  10607. // Testing video texture support
  10608. if (this._videoTextureSupported === undefined) {
  10609. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10610. if (this._gl.getError() !== 0) {
  10611. this._videoTextureSupported = false;
  10612. }
  10613. else {
  10614. this._videoTextureSupported = true;
  10615. }
  10616. }
  10617. // Copy video through the current working canvas if video texture is not supported
  10618. if (!this._videoTextureSupported) {
  10619. if (!texture._workingCanvas) {
  10620. texture._workingCanvas = document.createElement("canvas");
  10621. var context = texture._workingCanvas.getContext("2d");
  10622. if (!context) {
  10623. throw new Error("Unable to get 2d context");
  10624. }
  10625. texture._workingContext = context;
  10626. texture._workingCanvas.width = texture.width;
  10627. texture._workingCanvas.height = texture.height;
  10628. }
  10629. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10630. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10631. }
  10632. else {
  10633. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10634. }
  10635. if (texture.generateMipMaps) {
  10636. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10637. }
  10638. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10639. this.resetTextureCache();
  10640. texture.isReady = true;
  10641. }
  10642. catch (ex) {
  10643. // Something unexpected
  10644. // Let's disable the texture
  10645. texture._isDisabled = true;
  10646. }
  10647. };
  10648. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10649. var fullOptions = new RenderTargetCreationOptions();
  10650. if (options !== undefined && typeof options === "object") {
  10651. fullOptions.generateMipMaps = options.generateMipMaps;
  10652. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10653. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10654. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10655. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10656. }
  10657. else {
  10658. fullOptions.generateMipMaps = options;
  10659. fullOptions.generateDepthBuffer = true;
  10660. fullOptions.generateStencilBuffer = false;
  10661. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10662. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10663. }
  10664. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10665. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10666. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10667. }
  10668. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10669. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10670. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10671. }
  10672. var gl = this._gl;
  10673. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10674. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10675. var width = size.width || size;
  10676. var height = size.height || size;
  10677. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10678. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10679. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10680. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10681. }
  10682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10686. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10687. // Create the framebuffer
  10688. var framebuffer = gl.createFramebuffer();
  10689. this.bindUnboundFramebuffer(framebuffer);
  10690. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10691. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10692. if (fullOptions.generateMipMaps) {
  10693. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10694. }
  10695. // Unbind
  10696. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10697. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10698. this.bindUnboundFramebuffer(null);
  10699. texture._framebuffer = framebuffer;
  10700. texture.baseWidth = width;
  10701. texture.baseHeight = height;
  10702. texture.width = width;
  10703. texture.height = height;
  10704. texture.isReady = true;
  10705. texture.samples = 1;
  10706. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10707. texture.samplingMode = fullOptions.samplingMode;
  10708. texture.type = fullOptions.type;
  10709. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10710. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10711. this.resetTextureCache();
  10712. this._internalTexturesCache.push(texture);
  10713. return texture;
  10714. };
  10715. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10716. var generateMipMaps = false;
  10717. var generateDepthBuffer = true;
  10718. var generateStencilBuffer = false;
  10719. var generateDepthTexture = false;
  10720. var textureCount = 1;
  10721. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10722. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10723. var types = [], samplingModes = [];
  10724. if (options !== undefined) {
  10725. generateMipMaps = options.generateMipMaps;
  10726. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10727. generateStencilBuffer = options.generateStencilBuffer;
  10728. generateDepthTexture = options.generateDepthTexture;
  10729. textureCount = options.textureCount || 1;
  10730. if (options.types) {
  10731. types = options.types;
  10732. }
  10733. if (options.samplingModes) {
  10734. samplingModes = options.samplingModes;
  10735. }
  10736. }
  10737. var gl = this._gl;
  10738. // Create the framebuffer
  10739. var framebuffer = gl.createFramebuffer();
  10740. this.bindUnboundFramebuffer(framebuffer);
  10741. var width = size.width || size;
  10742. var height = size.height || size;
  10743. var textures = [];
  10744. var attachments = [];
  10745. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10746. for (var i = 0; i < textureCount; i++) {
  10747. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10748. var type = types[i] || defaultType;
  10749. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10750. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10751. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10752. }
  10753. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10754. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10755. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10756. }
  10757. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10758. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10759. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10760. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10761. }
  10762. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10763. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10764. textures.push(texture);
  10765. attachments.push(attachment);
  10766. gl.activeTexture(gl["TEXTURE" + i]);
  10767. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10772. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10773. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10774. if (generateMipMaps) {
  10775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10776. }
  10777. // Unbind
  10778. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10779. texture._framebuffer = framebuffer;
  10780. texture._depthStencilBuffer = depthStencilBuffer;
  10781. texture.baseWidth = width;
  10782. texture.baseHeight = height;
  10783. texture.width = width;
  10784. texture.height = height;
  10785. texture.isReady = true;
  10786. texture.samples = 1;
  10787. texture.generateMipMaps = generateMipMaps;
  10788. texture.samplingMode = samplingMode;
  10789. texture.type = type;
  10790. texture._generateDepthBuffer = generateDepthBuffer;
  10791. texture._generateStencilBuffer = generateStencilBuffer;
  10792. this._internalTexturesCache.push(texture);
  10793. }
  10794. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10795. // Depth texture
  10796. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10797. gl.activeTexture(gl.TEXTURE0);
  10798. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10803. 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);
  10804. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10805. depthTexture._framebuffer = framebuffer;
  10806. depthTexture.baseWidth = width;
  10807. depthTexture.baseHeight = height;
  10808. depthTexture.width = width;
  10809. depthTexture.height = height;
  10810. depthTexture.isReady = true;
  10811. depthTexture.samples = 1;
  10812. depthTexture.generateMipMaps = generateMipMaps;
  10813. depthTexture.samplingMode = gl.NEAREST;
  10814. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10815. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10816. textures.push(depthTexture);
  10817. this._internalTexturesCache.push(depthTexture);
  10818. }
  10819. gl.drawBuffers(attachments);
  10820. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10821. this.bindUnboundFramebuffer(null);
  10822. this.resetTextureCache();
  10823. return textures;
  10824. };
  10825. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10826. if (samples === void 0) { samples = 1; }
  10827. var depthStencilBuffer = null;
  10828. var gl = this._gl;
  10829. // Create the depth/stencil buffer
  10830. if (generateStencilBuffer) {
  10831. depthStencilBuffer = gl.createRenderbuffer();
  10832. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10833. if (samples > 1) {
  10834. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10835. }
  10836. else {
  10837. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10838. }
  10839. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10840. }
  10841. else if (generateDepthBuffer) {
  10842. depthStencilBuffer = gl.createRenderbuffer();
  10843. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10844. if (samples > 1) {
  10845. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10846. }
  10847. else {
  10848. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10849. }
  10850. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10851. }
  10852. return depthStencilBuffer;
  10853. };
  10854. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10855. if (this.webGLVersion < 2 || !texture) {
  10856. return 1;
  10857. }
  10858. if (texture.samples === samples) {
  10859. return samples;
  10860. }
  10861. var gl = this._gl;
  10862. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10863. // Dispose previous render buffers
  10864. if (texture._depthStencilBuffer) {
  10865. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10866. }
  10867. if (texture._MSAAFramebuffer) {
  10868. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10869. }
  10870. if (texture._MSAARenderBuffer) {
  10871. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10872. }
  10873. if (samples > 1) {
  10874. var framebuffer = gl.createFramebuffer();
  10875. if (!framebuffer) {
  10876. throw new Error("Unable to create multi sampled framebuffer");
  10877. }
  10878. texture._MSAAFramebuffer = framebuffer;
  10879. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10880. var colorRenderbuffer = gl.createRenderbuffer();
  10881. if (!colorRenderbuffer) {
  10882. throw new Error("Unable to create multi sampled framebuffer");
  10883. }
  10884. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10885. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10886. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10887. texture._MSAARenderBuffer = colorRenderbuffer;
  10888. }
  10889. else {
  10890. this.bindUnboundFramebuffer(texture._framebuffer);
  10891. }
  10892. texture.samples = samples;
  10893. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10894. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10895. this.bindUnboundFramebuffer(null);
  10896. return samples;
  10897. };
  10898. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10899. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10900. };
  10901. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10902. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10903. };
  10904. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10905. var gl = this._gl;
  10906. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10907. var generateMipMaps = true;
  10908. var generateDepthBuffer = true;
  10909. var generateStencilBuffer = false;
  10910. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10911. if (options !== undefined) {
  10912. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10913. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10914. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10915. if (options.samplingMode !== undefined) {
  10916. samplingMode = options.samplingMode;
  10917. }
  10918. }
  10919. texture.isCube = true;
  10920. texture.generateMipMaps = generateMipMaps;
  10921. texture.samples = 1;
  10922. texture.samplingMode = samplingMode;
  10923. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10924. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10925. for (var face = 0; face < 6; face++) {
  10926. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10927. }
  10928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10932. // Create the framebuffer
  10933. var framebuffer = gl.createFramebuffer();
  10934. this.bindUnboundFramebuffer(framebuffer);
  10935. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10936. // Mipmaps
  10937. if (texture.generateMipMaps) {
  10938. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10940. }
  10941. // Unbind
  10942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10944. this.bindUnboundFramebuffer(null);
  10945. texture._framebuffer = framebuffer;
  10946. texture.width = size;
  10947. texture.height = size;
  10948. texture.isReady = true;
  10949. this.resetTextureCache();
  10950. this._internalTexturesCache.push(texture);
  10951. return texture;
  10952. };
  10953. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10954. var _this = this;
  10955. if (onLoad === void 0) { onLoad = null; }
  10956. if (onError === void 0) { onError = null; }
  10957. if (forcedExtension === void 0) { forcedExtension = null; }
  10958. var callback = function (loadData) {
  10959. if (!loadData) {
  10960. if (onLoad) {
  10961. onLoad(null);
  10962. }
  10963. return;
  10964. }
  10965. var texture = loadData.texture;
  10966. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10967. texture._lodGenerationScale = scale;
  10968. texture._lodGenerationOffset = offset;
  10969. if (_this._caps.textureLOD) {
  10970. // Do not add extra process if texture lod is supported.
  10971. if (onLoad) {
  10972. onLoad(texture);
  10973. }
  10974. return;
  10975. }
  10976. var mipSlices = 3;
  10977. var gl = _this._gl;
  10978. var width = loadData.width;
  10979. if (!width) {
  10980. return;
  10981. }
  10982. var textures = [];
  10983. for (var i = 0; i < mipSlices; i++) {
  10984. //compute LOD from even spacing in smoothness (matching shader calculation)
  10985. var smoothness = i / (mipSlices - 1);
  10986. var roughness = 1 - smoothness;
  10987. var minLODIndex = offset; // roughness = 0
  10988. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10989. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10990. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10991. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10992. glTextureFromLod.isCube = true;
  10993. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10995. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10998. if (loadData.isDDS) {
  10999. var info = loadData.info;
  11000. var data = loadData.data;
  11001. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11002. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11003. }
  11004. else {
  11005. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11006. }
  11007. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11008. // Wrap in a base texture for easy binding.
  11009. var lodTexture = new BABYLON.BaseTexture(scene);
  11010. lodTexture.isCube = true;
  11011. lodTexture._texture = glTextureFromLod;
  11012. glTextureFromLod.isReady = true;
  11013. textures.push(lodTexture);
  11014. }
  11015. texture._lodTextureHigh = textures[2];
  11016. texture._lodTextureMid = textures[1];
  11017. texture._lodTextureLow = textures[0];
  11018. if (onLoad) {
  11019. onLoad(texture);
  11020. }
  11021. };
  11022. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11023. };
  11024. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11025. var _this = this;
  11026. if (onLoad === void 0) { onLoad = null; }
  11027. if (onError === void 0) { onError = null; }
  11028. if (forcedExtension === void 0) { forcedExtension = null; }
  11029. var gl = this._gl;
  11030. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11031. texture.isCube = true;
  11032. texture.url = rootUrl;
  11033. texture.generateMipMaps = !noMipmap;
  11034. if (!this._doNotHandleContextLost) {
  11035. texture._extension = forcedExtension;
  11036. texture._files = files;
  11037. }
  11038. var isKTX = false;
  11039. var isDDS = false;
  11040. var lastDot = rootUrl.lastIndexOf('.');
  11041. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11042. if (this._textureFormatInUse) {
  11043. extension = this._textureFormatInUse;
  11044. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11045. isKTX = true;
  11046. }
  11047. else {
  11048. isDDS = (extension === ".dds");
  11049. }
  11050. var onerror = function (request, exception) {
  11051. if (onError && request) {
  11052. onError(request.status + " " + request.statusText, exception);
  11053. }
  11054. };
  11055. if (isKTX) {
  11056. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11057. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11058. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11059. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11060. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11061. ktx.uploadLevels(_this._gl, !noMipmap);
  11062. _this.setCubeMapTextureParams(gl, loadMipmap);
  11063. texture.width = ktx.pixelWidth;
  11064. texture.height = ktx.pixelHeight;
  11065. texture.isReady = true;
  11066. }, undefined, undefined, true, onerror);
  11067. }
  11068. else if (isDDS) {
  11069. if (files && files.length === 6) {
  11070. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11071. var info;
  11072. var loadMipmap = false;
  11073. var width = 0;
  11074. for (var index = 0; index < imgs.length; index++) {
  11075. var data = imgs[index];
  11076. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11077. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11078. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11079. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11080. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11081. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11082. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11083. }
  11084. texture.width = info.width;
  11085. texture.height = info.height;
  11086. texture.type = info.textureType;
  11087. width = info.width;
  11088. }
  11089. _this.setCubeMapTextureParams(gl, loadMipmap);
  11090. texture.isReady = true;
  11091. if (onLoad) {
  11092. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11093. }
  11094. }, files, onError);
  11095. }
  11096. else {
  11097. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11098. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11099. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11100. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11101. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11102. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11103. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11104. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11105. }
  11106. _this.setCubeMapTextureParams(gl, loadMipmap);
  11107. texture.width = info.width;
  11108. texture.height = info.height;
  11109. texture.isReady = true;
  11110. texture.type = info.textureType;
  11111. if (onLoad) {
  11112. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11113. }
  11114. }, undefined, undefined, true, onerror);
  11115. }
  11116. }
  11117. else {
  11118. if (!files) {
  11119. throw new Error("Cannot load cubemap because files were not defined");
  11120. }
  11121. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11122. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11123. var height = width;
  11124. _this._prepareWorkingCanvas();
  11125. if (!_this._workingCanvas || !_this._workingContext) {
  11126. return;
  11127. }
  11128. _this._workingCanvas.width = width;
  11129. _this._workingCanvas.height = height;
  11130. var faces = [
  11131. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11132. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11133. ];
  11134. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11135. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11136. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11137. for (var index = 0; index < faces.length; index++) {
  11138. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11139. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11140. }
  11141. if (!noMipmap) {
  11142. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11143. }
  11144. _this.setCubeMapTextureParams(gl, !noMipmap);
  11145. texture.width = width;
  11146. texture.height = height;
  11147. texture.isReady = true;
  11148. if (format) {
  11149. texture.format = format;
  11150. }
  11151. texture.onLoadedObservable.notifyObservers(texture);
  11152. texture.onLoadedObservable.clear();
  11153. if (onLoad) {
  11154. onLoad();
  11155. }
  11156. }, files, onError);
  11157. }
  11158. this._internalTexturesCache.push(texture);
  11159. return texture;
  11160. };
  11161. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11167. this.resetTextureCache();
  11168. };
  11169. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11170. if (compression === void 0) { compression = null; }
  11171. if (level === void 0) { level = 0; }
  11172. texture._bufferViewArray = data;
  11173. texture.format = format;
  11174. texture.type = type;
  11175. texture.invertY = invertY;
  11176. texture._compression = compression;
  11177. var gl = this._gl;
  11178. var textureType = this._getWebGLTextureType(type);
  11179. var internalFormat = this._getInternalFormat(format);
  11180. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11181. var needConversion = false;
  11182. if (internalFormat === gl.RGB) {
  11183. internalFormat = gl.RGBA;
  11184. needConversion = true;
  11185. }
  11186. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11187. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11188. if (texture.width % 4 !== 0) {
  11189. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11190. }
  11191. // Data are known to be in +X +Y +Z -X -Y -Z
  11192. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11193. var faceData = data[faceIndex];
  11194. if (compression) {
  11195. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11196. }
  11197. else {
  11198. if (needConversion) {
  11199. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11200. }
  11201. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11202. }
  11203. }
  11204. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11205. if (isPot && texture.generateMipMaps && level === 0) {
  11206. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11207. }
  11208. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11209. this.resetTextureCache();
  11210. texture.isReady = true;
  11211. };
  11212. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11213. if (compression === void 0) { compression = null; }
  11214. var gl = this._gl;
  11215. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11216. texture.isCube = true;
  11217. texture.generateMipMaps = generateMipMaps;
  11218. texture.format = format;
  11219. texture.type = type;
  11220. if (!this._doNotHandleContextLost) {
  11221. texture._bufferViewArray = data;
  11222. }
  11223. var textureType = this._getWebGLTextureType(type);
  11224. var internalFormat = this._getInternalFormat(format);
  11225. if (internalFormat === gl.RGB) {
  11226. internalFormat = gl.RGBA;
  11227. }
  11228. var width = size;
  11229. var height = width;
  11230. texture.width = width;
  11231. texture.height = height;
  11232. // Double check on POT to generate Mips.
  11233. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11234. if (!isPot) {
  11235. generateMipMaps = false;
  11236. }
  11237. // Upload data if needed. The texture won't be ready until then.
  11238. if (data) {
  11239. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11240. }
  11241. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11242. // Filters
  11243. if (data && generateMipMaps) {
  11244. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11245. }
  11246. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11249. }
  11250. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11252. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11253. }
  11254. else {
  11255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11256. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11258. }
  11259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11261. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11262. return texture;
  11263. };
  11264. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11265. var _this = this;
  11266. if (onLoad === void 0) { onLoad = null; }
  11267. if (onError === void 0) { onError = null; }
  11268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11269. if (invertY === void 0) { invertY = false; }
  11270. var gl = this._gl;
  11271. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11272. scene._addPendingData(texture);
  11273. texture.url = url;
  11274. this._internalTexturesCache.push(texture);
  11275. var onerror = function (request, exception) {
  11276. scene._removePendingData(texture);
  11277. if (onError && request) {
  11278. onError(request.status + " " + request.statusText, exception);
  11279. }
  11280. };
  11281. var internalCallback = function (data) {
  11282. var width = texture.width;
  11283. var faceDataArrays = callback(data);
  11284. if (!faceDataArrays) {
  11285. return;
  11286. }
  11287. if (mipmmapGenerator) {
  11288. var textureType = _this._getWebGLTextureType(type);
  11289. var internalFormat = _this._getInternalFormat(format);
  11290. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11291. var needConversion = false;
  11292. if (internalFormat === gl.RGB) {
  11293. internalFormat = gl.RGBA;
  11294. needConversion = true;
  11295. }
  11296. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11297. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11298. var mipData = mipmmapGenerator(faceDataArrays);
  11299. for (var level = 0; level < mipData.length; level++) {
  11300. var mipSize = width >> level;
  11301. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11302. var mipFaceData = mipData[level][faceIndex];
  11303. if (needConversion) {
  11304. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11305. }
  11306. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11307. }
  11308. }
  11309. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11310. }
  11311. else {
  11312. texture.generateMipMaps = !noMipmap;
  11313. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11314. }
  11315. texture.isReady = true;
  11316. _this.resetTextureCache();
  11317. scene._removePendingData(texture);
  11318. if (onLoad) {
  11319. onLoad();
  11320. }
  11321. };
  11322. BABYLON.Tools.LoadFile(url, function (data) {
  11323. internalCallback(data);
  11324. }, undefined, scene.database, true, onerror);
  11325. return texture;
  11326. };
  11327. ;
  11328. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11329. if (compression === void 0) { compression = null; }
  11330. var internalFormat = this._getInternalFormat(format);
  11331. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11332. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11333. if (!this._doNotHandleContextLost) {
  11334. texture._bufferView = data;
  11335. texture.format = format;
  11336. texture.invertY = invertY;
  11337. texture._compression = compression;
  11338. }
  11339. if (texture.width % 4 !== 0) {
  11340. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11341. }
  11342. if (compression && data) {
  11343. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11344. }
  11345. else {
  11346. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11347. }
  11348. if (texture.generateMipMaps) {
  11349. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11350. }
  11351. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11352. this.resetTextureCache();
  11353. texture.isReady = true;
  11354. };
  11355. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11356. if (compression === void 0) { compression = null; }
  11357. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11358. texture.baseWidth = width;
  11359. texture.baseHeight = height;
  11360. texture.baseDepth = depth;
  11361. texture.width = width;
  11362. texture.height = height;
  11363. texture.depth = depth;
  11364. texture.format = format;
  11365. texture.generateMipMaps = generateMipMaps;
  11366. texture.samplingMode = samplingMode;
  11367. texture.is3D = true;
  11368. if (!this._doNotHandleContextLost) {
  11369. texture._bufferView = data;
  11370. }
  11371. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11372. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11373. // Filters
  11374. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11375. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11376. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11377. if (generateMipMaps) {
  11378. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11379. }
  11380. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11381. this._internalTexturesCache.push(texture);
  11382. return texture;
  11383. };
  11384. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11385. var gl = this._gl;
  11386. if (!gl) {
  11387. return;
  11388. }
  11389. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11392. if (!noMipmap && !isCompressed) {
  11393. gl.generateMipmap(gl.TEXTURE_2D);
  11394. }
  11395. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11396. this.resetTextureCache();
  11397. if (scene) {
  11398. scene._removePendingData(texture);
  11399. }
  11400. texture.onLoadedObservable.notifyObservers(texture);
  11401. texture.onLoadedObservable.clear();
  11402. };
  11403. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11404. var _this = this;
  11405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11406. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11407. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11408. var gl = this._gl;
  11409. if (!gl) {
  11410. return;
  11411. }
  11412. if (!texture._webGLTexture) {
  11413. this.resetTextureCache();
  11414. if (scene) {
  11415. scene._removePendingData(texture);
  11416. }
  11417. return;
  11418. }
  11419. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11420. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11421. texture.baseWidth = width;
  11422. texture.baseHeight = height;
  11423. texture.width = potWidth;
  11424. texture.height = potHeight;
  11425. texture.isReady = true;
  11426. if (processFunction(potWidth, potHeight, function () {
  11427. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11428. })) {
  11429. // Returning as texture needs extra async steps
  11430. return;
  11431. }
  11432. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11433. };
  11434. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11435. // Create new RGBA data container.
  11436. var rgbaData;
  11437. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11438. rgbaData = new Float32Array(width * height * 4);
  11439. }
  11440. else {
  11441. rgbaData = new Uint32Array(width * height * 4);
  11442. }
  11443. // Convert each pixel.
  11444. for (var x = 0; x < width; x++) {
  11445. for (var y = 0; y < height; y++) {
  11446. var index = (y * width + x) * 3;
  11447. var newIndex = (y * width + x) * 4;
  11448. // Map Old Value to new value.
  11449. rgbaData[newIndex + 0] = rgbData[index + 0];
  11450. rgbaData[newIndex + 1] = rgbData[index + 1];
  11451. rgbaData[newIndex + 2] = rgbData[index + 2];
  11452. // Add fully opaque alpha channel.
  11453. rgbaData[newIndex + 3] = 1;
  11454. }
  11455. }
  11456. return rgbaData;
  11457. };
  11458. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11459. var gl = this._gl;
  11460. if (texture._framebuffer) {
  11461. gl.deleteFramebuffer(texture._framebuffer);
  11462. texture._framebuffer = null;
  11463. }
  11464. if (texture._depthStencilBuffer) {
  11465. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11466. texture._depthStencilBuffer = null;
  11467. }
  11468. if (texture._MSAAFramebuffer) {
  11469. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11470. texture._MSAAFramebuffer = null;
  11471. }
  11472. if (texture._MSAARenderBuffer) {
  11473. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11474. texture._MSAARenderBuffer = null;
  11475. }
  11476. };
  11477. Engine.prototype._releaseTexture = function (texture) {
  11478. var gl = this._gl;
  11479. this._releaseFramebufferObjects(texture);
  11480. gl.deleteTexture(texture._webGLTexture);
  11481. // Unbind channels
  11482. this.unbindAllTextures();
  11483. var index = this._internalTexturesCache.indexOf(texture);
  11484. if (index !== -1) {
  11485. this._internalTexturesCache.splice(index, 1);
  11486. }
  11487. // Integrated fixed lod samplers.
  11488. if (texture._lodTextureHigh) {
  11489. texture._lodTextureHigh.dispose();
  11490. }
  11491. if (texture._lodTextureMid) {
  11492. texture._lodTextureMid.dispose();
  11493. }
  11494. if (texture._lodTextureLow) {
  11495. texture._lodTextureLow.dispose();
  11496. }
  11497. };
  11498. Engine.prototype.setProgram = function (program) {
  11499. if (this._currentProgram !== program) {
  11500. this._gl.useProgram(program);
  11501. this._currentProgram = program;
  11502. }
  11503. };
  11504. Engine.prototype.bindSamplers = function (effect) {
  11505. this.setProgram(effect.getProgram());
  11506. var samplers = effect.getSamplers();
  11507. for (var index = 0; index < samplers.length; index++) {
  11508. var uniform = effect.getUniform(samplers[index]);
  11509. this._gl.uniform1i(uniform, index);
  11510. }
  11511. this._currentEffect = null;
  11512. };
  11513. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11514. if (this._activeTextureChannel !== textureChannel) {
  11515. this._gl.activeTexture(textureChannel);
  11516. this._activeTextureChannel = textureChannel;
  11517. }
  11518. };
  11519. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11520. if (this._boundTexturesCache[this._activeTextureChannel] !== texture) {
  11521. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11522. this._boundTexturesCache[this._activeTextureChannel] = texture;
  11523. }
  11524. };
  11525. Engine.prototype._bindTexture = function (channel, texture) {
  11526. if (channel < 0) {
  11527. return;
  11528. }
  11529. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11530. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11531. };
  11532. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11533. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11534. };
  11535. Engine.prototype.unbindAllTextures = function () {
  11536. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11537. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11538. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11539. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11540. if (this.webGLVersion > 1) {
  11541. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11542. }
  11543. }
  11544. };
  11545. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11546. if (channel < 0) {
  11547. return;
  11548. }
  11549. if (this._setTexture(channel, texture)) {
  11550. this._gl.uniform1i(uniform, channel);
  11551. }
  11552. };
  11553. Engine.prototype._setTexture = function (channel, texture) {
  11554. // Not ready?
  11555. if (!texture) {
  11556. if (this._boundTexturesCache[channel] != null) {
  11557. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11558. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11559. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11560. if (this.webGLVersion > 1) {
  11561. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11562. }
  11563. }
  11564. return false;
  11565. }
  11566. // Video
  11567. var alreadyActivated = false;
  11568. if (texture.video) {
  11569. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11570. alreadyActivated = true;
  11571. texture.update();
  11572. }
  11573. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11574. texture.delayLoad();
  11575. return false;
  11576. }
  11577. var internalTexture;
  11578. if (texture.isReady()) {
  11579. internalTexture = texture.getInternalTexture();
  11580. }
  11581. else if (texture.isCube) {
  11582. internalTexture = this.emptyCubeTexture;
  11583. }
  11584. else if (texture.is3D) {
  11585. internalTexture = this.emptyTexture3D;
  11586. }
  11587. else {
  11588. internalTexture = this.emptyTexture;
  11589. }
  11590. if (!alreadyActivated) {
  11591. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11592. }
  11593. if (this._boundTexturesCache[this._activeTextureChannel] === internalTexture) {
  11594. return false;
  11595. }
  11596. if (internalTexture && internalTexture.is3D) {
  11597. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11598. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11599. internalTexture._cachedWrapU = texture.wrapU;
  11600. switch (texture.wrapU) {
  11601. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11602. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11603. break;
  11604. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11605. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11606. break;
  11607. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11608. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11609. break;
  11610. }
  11611. }
  11612. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11613. internalTexture._cachedWrapV = texture.wrapV;
  11614. switch (texture.wrapV) {
  11615. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11616. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11617. break;
  11618. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11619. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11620. break;
  11621. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11622. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11623. break;
  11624. }
  11625. }
  11626. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11627. internalTexture._cachedWrapR = texture.wrapR;
  11628. switch (texture.wrapV) {
  11629. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11630. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11631. break;
  11632. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11633. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11634. break;
  11635. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11636. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11637. break;
  11638. }
  11639. }
  11640. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11641. }
  11642. else if (internalTexture && internalTexture.isCube) {
  11643. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11644. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11645. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11646. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11647. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11648. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11649. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11650. }
  11651. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11652. }
  11653. else {
  11654. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11655. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11656. internalTexture._cachedWrapU = texture.wrapU;
  11657. switch (texture.wrapU) {
  11658. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11659. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11660. break;
  11661. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11663. break;
  11664. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11665. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11666. break;
  11667. }
  11668. }
  11669. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11670. internalTexture._cachedWrapV = texture.wrapV;
  11671. switch (texture.wrapV) {
  11672. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11673. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11674. break;
  11675. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11676. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11677. break;
  11678. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11679. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11680. break;
  11681. }
  11682. }
  11683. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11684. }
  11685. return true;
  11686. };
  11687. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11688. if (channel < 0 || !uniform) {
  11689. return;
  11690. }
  11691. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11692. this._textureUnits = new Int32Array(textures.length);
  11693. }
  11694. for (var i = 0; i < textures.length; i++) {
  11695. this._textureUnits[i] = channel + i;
  11696. }
  11697. this._gl.uniform1iv(uniform, this._textureUnits);
  11698. for (var index = 0; index < textures.length; index++) {
  11699. this._setTexture(channel + index, textures[index]);
  11700. }
  11701. };
  11702. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11703. var internalTexture = texture.getInternalTexture();
  11704. if (!internalTexture) {
  11705. return;
  11706. }
  11707. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11708. var value = texture.anisotropicFilteringLevel;
  11709. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11710. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11711. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11712. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11713. }
  11714. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11715. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11716. internalTexture._cachedAnisotropicFilteringLevel = value;
  11717. }
  11718. };
  11719. Engine.prototype.readPixels = function (x, y, width, height) {
  11720. var data = new Uint8Array(height * width * 4);
  11721. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11722. return data;
  11723. };
  11724. /**
  11725. * Add an externaly attached data from its key.
  11726. * This method call will fail and return false, if such key already exists.
  11727. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11728. * @param key the unique key that identifies the data
  11729. * @param data the data object to associate to the key for this Engine instance
  11730. * @return true if no such key were already present and the data was added successfully, false otherwise
  11731. */
  11732. Engine.prototype.addExternalData = function (key, data) {
  11733. if (!this._externalData) {
  11734. this._externalData = new BABYLON.StringDictionary();
  11735. }
  11736. return this._externalData.add(key, data);
  11737. };
  11738. /**
  11739. * Get an externaly attached data from its key
  11740. * @param key the unique key that identifies the data
  11741. * @return the associated data, if present (can be null), or undefined if not present
  11742. */
  11743. Engine.prototype.getExternalData = function (key) {
  11744. if (!this._externalData) {
  11745. this._externalData = new BABYLON.StringDictionary();
  11746. }
  11747. return this._externalData.get(key);
  11748. };
  11749. /**
  11750. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11751. * @param key the unique key that identifies the data
  11752. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11753. * @return the associated data, can be null if the factory returned null.
  11754. */
  11755. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11756. if (!this._externalData) {
  11757. this._externalData = new BABYLON.StringDictionary();
  11758. }
  11759. return this._externalData.getOrAddWithFactory(key, factory);
  11760. };
  11761. /**
  11762. * Remove an externaly attached data from the Engine instance
  11763. * @param key the unique key that identifies the data
  11764. * @return true if the data was successfully removed, false if it doesn't exist
  11765. */
  11766. Engine.prototype.removeExternalData = function (key) {
  11767. if (!this._externalData) {
  11768. this._externalData = new BABYLON.StringDictionary();
  11769. }
  11770. return this._externalData.remove(key);
  11771. };
  11772. Engine.prototype.unbindAllAttributes = function () {
  11773. if (this._mustWipeVertexAttributes) {
  11774. this._mustWipeVertexAttributes = false;
  11775. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11776. this._gl.disableVertexAttribArray(i);
  11777. this._vertexAttribArraysEnabled[i] = false;
  11778. this._currentBufferPointers[i].active = false;
  11779. }
  11780. return;
  11781. }
  11782. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11783. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11784. continue;
  11785. }
  11786. this._gl.disableVertexAttribArray(i);
  11787. this._vertexAttribArraysEnabled[i] = false;
  11788. this._currentBufferPointers[i].active = false;
  11789. }
  11790. };
  11791. Engine.prototype.releaseEffects = function () {
  11792. for (var name in this._compiledEffects) {
  11793. this._deleteProgram(this._compiledEffects[name]._program);
  11794. }
  11795. this._compiledEffects = {};
  11796. };
  11797. // Dispose
  11798. Engine.prototype.dispose = function () {
  11799. this.hideLoadingUI();
  11800. this.stopRenderLoop();
  11801. // Release postProcesses
  11802. while (this.postProcesses.length) {
  11803. this.postProcesses[0].dispose();
  11804. }
  11805. // Empty texture
  11806. if (this._emptyTexture) {
  11807. this._releaseTexture(this._emptyTexture);
  11808. this._emptyTexture = null;
  11809. }
  11810. if (this._emptyCubeTexture) {
  11811. this._releaseTexture(this._emptyCubeTexture);
  11812. this._emptyCubeTexture = null;
  11813. }
  11814. // Rescale PP
  11815. if (this._rescalePostProcess) {
  11816. this._rescalePostProcess.dispose();
  11817. }
  11818. // Release scenes
  11819. while (this.scenes.length) {
  11820. this.scenes[0].dispose();
  11821. }
  11822. // Release audio engine
  11823. if (Engine.audioEngine) {
  11824. Engine.audioEngine.dispose();
  11825. }
  11826. // Release effects
  11827. this.releaseEffects();
  11828. // Unbind
  11829. this.unbindAllAttributes();
  11830. if (this._dummyFramebuffer) {
  11831. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11832. }
  11833. //WebVR
  11834. this.disableVR();
  11835. // Events
  11836. if (BABYLON.Tools.IsWindowObjectExist()) {
  11837. window.removeEventListener("blur", this._onBlur);
  11838. window.removeEventListener("focus", this._onFocus);
  11839. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11840. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11841. if (this._renderingCanvas) {
  11842. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11843. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11844. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11845. if (!this._doNotHandleContextLost) {
  11846. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11847. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11848. }
  11849. }
  11850. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11851. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11852. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11853. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11854. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11855. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11856. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11857. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11858. if (this._onVrDisplayConnect) {
  11859. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11860. if (this._onVrDisplayDisconnect) {
  11861. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11862. }
  11863. if (this._onVrDisplayPresentChange) {
  11864. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11865. }
  11866. this._onVrDisplayConnect = null;
  11867. this._onVrDisplayDisconnect = null;
  11868. }
  11869. }
  11870. // Remove from Instances
  11871. var index = Engine.Instances.indexOf(this);
  11872. if (index >= 0) {
  11873. Engine.Instances.splice(index, 1);
  11874. }
  11875. this._workingCanvas = null;
  11876. this._workingContext = null;
  11877. this._currentBufferPointers = [];
  11878. this._renderingCanvas = null;
  11879. this._currentProgram = null;
  11880. this.onResizeObservable.clear();
  11881. this.onCanvasBlurObservable.clear();
  11882. this.onCanvasFocusObservable.clear();
  11883. this.onCanvasPointerOutObservable.clear();
  11884. this.onBeginFrameObservable.clear();
  11885. this.onEndFrameObservable.clear();
  11886. BABYLON.Effect.ResetCache();
  11887. };
  11888. // Loading screen
  11889. Engine.prototype.displayLoadingUI = function () {
  11890. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11891. return;
  11892. }
  11893. var loadingScreen = this.loadingScreen;
  11894. if (loadingScreen) {
  11895. loadingScreen.displayLoadingUI();
  11896. }
  11897. };
  11898. Engine.prototype.hideLoadingUI = function () {
  11899. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11900. return;
  11901. }
  11902. var loadingScreen = this.loadingScreen;
  11903. if (loadingScreen) {
  11904. loadingScreen.hideLoadingUI();
  11905. }
  11906. };
  11907. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11908. get: function () {
  11909. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11910. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11911. return this._loadingScreen;
  11912. },
  11913. set: function (loadingScreen) {
  11914. this._loadingScreen = loadingScreen;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11920. set: function (text) {
  11921. this.loadingScreen.loadingUIText = text;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11927. set: function (color) {
  11928. this.loadingScreen.loadingUIBackgroundColor = color;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Engine.prototype.attachContextLostEvent = function (callback) {
  11934. if (this._renderingCanvas) {
  11935. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11936. }
  11937. };
  11938. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11939. if (this._renderingCanvas) {
  11940. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11941. }
  11942. };
  11943. Engine.prototype.getVertexShaderSource = function (program) {
  11944. var shaders = this._gl.getAttachedShaders(program);
  11945. if (!shaders) {
  11946. return null;
  11947. }
  11948. return this._gl.getShaderSource(shaders[0]);
  11949. };
  11950. Engine.prototype.getFragmentShaderSource = function (program) {
  11951. var shaders = this._gl.getAttachedShaders(program);
  11952. if (!shaders) {
  11953. return null;
  11954. }
  11955. return this._gl.getShaderSource(shaders[1]);
  11956. };
  11957. Engine.prototype.getError = function () {
  11958. return this._gl.getError();
  11959. };
  11960. // FPS
  11961. Engine.prototype.getFps = function () {
  11962. return this._fps;
  11963. };
  11964. Engine.prototype.getDeltaTime = function () {
  11965. return this._deltaTime;
  11966. };
  11967. Engine.prototype._measureFps = function () {
  11968. this._performanceMonitor.sampleFrame();
  11969. this._fps = this._performanceMonitor.averageFPS;
  11970. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11971. };
  11972. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11973. if (faceIndex === void 0) { faceIndex = -1; }
  11974. var gl = this._gl;
  11975. if (!this._dummyFramebuffer) {
  11976. var dummy = gl.createFramebuffer();
  11977. if (!dummy) {
  11978. throw new Error("Unable to create dummy framebuffer");
  11979. }
  11980. this._dummyFramebuffer = dummy;
  11981. }
  11982. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11983. if (faceIndex > -1) {
  11984. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11985. }
  11986. else {
  11987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11988. }
  11989. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11990. var buffer;
  11991. switch (readType) {
  11992. case gl.UNSIGNED_BYTE:
  11993. buffer = new Uint8Array(4 * width * height);
  11994. readType = gl.UNSIGNED_BYTE;
  11995. break;
  11996. default:
  11997. buffer = new Float32Array(4 * width * height);
  11998. readType = gl.FLOAT;
  11999. break;
  12000. }
  12001. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12002. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12003. return buffer;
  12004. };
  12005. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12006. if (this._webGLVersion > 1) {
  12007. return this._caps.colorBufferFloat;
  12008. }
  12009. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  12010. };
  12011. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12012. if (this._webGLVersion > 1) {
  12013. return this._caps.colorBufferFloat;
  12014. }
  12015. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  12016. };
  12017. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12018. Engine.prototype._canRenderToFramebuffer = function (type) {
  12019. var gl = this._gl;
  12020. //clear existing errors
  12021. while (gl.getError() !== gl.NO_ERROR) { }
  12022. var successful = true;
  12023. var texture = gl.createTexture();
  12024. gl.bindTexture(gl.TEXTURE_2D, texture);
  12025. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12028. var fb = gl.createFramebuffer();
  12029. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12031. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12032. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12033. successful = successful && (gl.getError() === gl.NO_ERROR);
  12034. //try render by clearing frame buffer's color buffer
  12035. if (successful) {
  12036. gl.clear(gl.COLOR_BUFFER_BIT);
  12037. successful = successful && (gl.getError() === gl.NO_ERROR);
  12038. }
  12039. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12040. if (successful) {
  12041. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12042. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12043. var readFormat = gl.RGBA;
  12044. var readType = gl.UNSIGNED_BYTE;
  12045. var buffer = new Uint8Array(4);
  12046. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12047. successful = successful && (gl.getError() === gl.NO_ERROR);
  12048. }
  12049. //clean up
  12050. gl.deleteTexture(texture);
  12051. gl.deleteFramebuffer(fb);
  12052. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12053. //clear accumulated errors
  12054. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12055. return successful;
  12056. };
  12057. Engine.prototype._getWebGLTextureType = function (type) {
  12058. if (type === Engine.TEXTURETYPE_FLOAT) {
  12059. return this._gl.FLOAT;
  12060. }
  12061. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12062. // Add Half Float Constant.
  12063. return this._gl.HALF_FLOAT_OES;
  12064. }
  12065. return this._gl.UNSIGNED_BYTE;
  12066. };
  12067. ;
  12068. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12069. if (this._webGLVersion === 1) {
  12070. return this._gl.RGBA;
  12071. }
  12072. if (type === Engine.TEXTURETYPE_FLOAT) {
  12073. return this._gl.RGBA32F;
  12074. }
  12075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12076. return this._gl.RGBA16F;
  12077. }
  12078. return this._gl.RGBA;
  12079. };
  12080. ;
  12081. Engine.prototype.createQuery = function () {
  12082. return this._gl.createQuery();
  12083. };
  12084. Engine.prototype.deleteQuery = function (query) {
  12085. this._gl.deleteQuery(query);
  12086. return this;
  12087. };
  12088. Engine.prototype.isQueryResultAvailable = function (query) {
  12089. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12090. };
  12091. Engine.prototype.getQueryResult = function (query) {
  12092. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12093. };
  12094. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12095. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12096. this._gl.beginQuery(glAlgorithm, query);
  12097. return this;
  12098. };
  12099. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12100. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12101. this._gl.endQuery(glAlgorithm);
  12102. return this;
  12103. };
  12104. /* Time queries */
  12105. Engine.prototype._createTimeQuery = function () {
  12106. var timerQuery = this._caps.timerQuery;
  12107. if (timerQuery.createQueryEXT) {
  12108. return timerQuery.createQueryEXT();
  12109. }
  12110. return this.createQuery();
  12111. };
  12112. Engine.prototype._deleteTimeQuery = function (query) {
  12113. var timerQuery = this._caps.timerQuery;
  12114. if (timerQuery.deleteQueryEXT) {
  12115. timerQuery.deleteQueryEXT(query);
  12116. return;
  12117. }
  12118. this.deleteQuery(query);
  12119. };
  12120. Engine.prototype._getTimeQueryResult = function (query) {
  12121. var timerQuery = this._caps.timerQuery;
  12122. if (timerQuery.getQueryObjectEXT) {
  12123. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12124. }
  12125. return this.getQueryResult(query);
  12126. };
  12127. Engine.prototype._getTimeQueryAvailability = function (query) {
  12128. var timerQuery = this._caps.timerQuery;
  12129. if (timerQuery.getQueryObjectEXT) {
  12130. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12131. }
  12132. return this.isQueryResultAvailable(query);
  12133. };
  12134. Engine.prototype.startTimeQuery = function () {
  12135. var timerQuery = this._caps.timerQuery;
  12136. if (!timerQuery) {
  12137. return null;
  12138. }
  12139. var token = new BABYLON._TimeToken();
  12140. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12141. if (this._caps.canUseTimestampForTimerQuery) {
  12142. token._startTimeQuery = this._createTimeQuery();
  12143. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12144. }
  12145. else {
  12146. if (this._currentNonTimestampToken) {
  12147. return this._currentNonTimestampToken;
  12148. }
  12149. token._timeElapsedQuery = this._createTimeQuery();
  12150. if (timerQuery.beginQueryEXT) {
  12151. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12152. }
  12153. else {
  12154. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12155. }
  12156. this._currentNonTimestampToken = token;
  12157. }
  12158. return token;
  12159. };
  12160. Engine.prototype.endTimeQuery = function (token) {
  12161. var timerQuery = this._caps.timerQuery;
  12162. if (!timerQuery || !token) {
  12163. return -1;
  12164. }
  12165. if (this._caps.canUseTimestampForTimerQuery) {
  12166. if (!token._startTimeQuery) {
  12167. return -1;
  12168. }
  12169. if (!token._endTimeQuery) {
  12170. token._endTimeQuery = this._createTimeQuery();
  12171. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12172. }
  12173. }
  12174. else if (!token._timeElapsedQueryEnded) {
  12175. if (!token._timeElapsedQuery) {
  12176. return -1;
  12177. }
  12178. if (timerQuery.endQueryEXT) {
  12179. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12180. }
  12181. else {
  12182. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12183. }
  12184. token._timeElapsedQueryEnded = true;
  12185. }
  12186. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12187. var available = false;
  12188. if (token._endTimeQuery) {
  12189. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12190. }
  12191. else if (token._timeElapsedQuery) {
  12192. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12193. }
  12194. if (available && !disjoint) {
  12195. var result = 0;
  12196. if (this._caps.canUseTimestampForTimerQuery) {
  12197. if (!token._startTimeQuery || !token._endTimeQuery) {
  12198. return -1;
  12199. }
  12200. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12201. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12202. result = timeEnd - timeStart;
  12203. this._deleteTimeQuery(token._startTimeQuery);
  12204. this._deleteTimeQuery(token._endTimeQuery);
  12205. token._startTimeQuery = null;
  12206. token._endTimeQuery = null;
  12207. }
  12208. else {
  12209. if (!token._timeElapsedQuery) {
  12210. return -1;
  12211. }
  12212. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12213. this._deleteTimeQuery(token._timeElapsedQuery);
  12214. token._timeElapsedQuery = null;
  12215. token._timeElapsedQueryEnded = false;
  12216. this._currentNonTimestampToken = null;
  12217. }
  12218. return result;
  12219. }
  12220. return -1;
  12221. };
  12222. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12223. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12224. };
  12225. // Transform feedback
  12226. Engine.prototype.createTransformFeedback = function () {
  12227. return this._gl.createTransformFeedback();
  12228. };
  12229. Engine.prototype.deleteTransformFeedback = function (value) {
  12230. this._gl.deleteTransformFeedback(value);
  12231. };
  12232. Engine.prototype.bindTransformFeedback = function (value) {
  12233. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12234. };
  12235. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12236. if (usePoints === void 0) { usePoints = true; }
  12237. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12238. };
  12239. Engine.prototype.endTransformFeedback = function () {
  12240. this._gl.endTransformFeedback();
  12241. };
  12242. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12243. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12244. };
  12245. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12246. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12247. };
  12248. // Statics
  12249. Engine.isSupported = function () {
  12250. try {
  12251. var tempcanvas = document.createElement("canvas");
  12252. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12253. return gl != null && !!window.WebGLRenderingContext;
  12254. }
  12255. catch (e) {
  12256. return false;
  12257. }
  12258. };
  12259. Engine.Instances = new Array();
  12260. // Const statics
  12261. Engine._ALPHA_DISABLE = 0;
  12262. Engine._ALPHA_ADD = 1;
  12263. Engine._ALPHA_COMBINE = 2;
  12264. Engine._ALPHA_SUBTRACT = 3;
  12265. Engine._ALPHA_MULTIPLY = 4;
  12266. Engine._ALPHA_MAXIMIZED = 5;
  12267. Engine._ALPHA_ONEONE = 6;
  12268. Engine._ALPHA_PREMULTIPLIED = 7;
  12269. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12270. Engine._ALPHA_INTERPOLATE = 9;
  12271. Engine._ALPHA_SCREENMODE = 10;
  12272. Engine._DELAYLOADSTATE_NONE = 0;
  12273. Engine._DELAYLOADSTATE_LOADED = 1;
  12274. Engine._DELAYLOADSTATE_LOADING = 2;
  12275. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12276. Engine._TEXTUREFORMAT_ALPHA = 0;
  12277. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12278. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12279. Engine._TEXTUREFORMAT_RGB = 4;
  12280. Engine._TEXTUREFORMAT_RGBA = 5;
  12281. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12282. Engine._TEXTURETYPE_FLOAT = 1;
  12283. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12284. // Depht or Stencil test Constants.
  12285. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12286. 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.
  12287. 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.
  12288. 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.
  12289. 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.
  12290. 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.
  12291. 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.
  12292. 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.
  12293. // Stencil Actions Constants.
  12294. Engine._KEEP = 0x1E00;
  12295. Engine._REPLACE = 0x1E01;
  12296. Engine._INCR = 0x1E02;
  12297. Engine._DECR = 0x1E03;
  12298. Engine._INVERT = 0x150A;
  12299. Engine._INCR_WRAP = 0x8507;
  12300. Engine._DECR_WRAP = 0x8508;
  12301. // Texture rescaling mode
  12302. Engine._SCALEMODE_FLOOR = 1;
  12303. Engine._SCALEMODE_NEAREST = 2;
  12304. Engine._SCALEMODE_CEILING = 3;
  12305. // Updatable statics so stick with vars here
  12306. Engine.CollisionsEpsilon = 0.001;
  12307. Engine.CodeRepository = "src/";
  12308. Engine.ShadersRepository = "src/Shaders/";
  12309. return Engine;
  12310. }());
  12311. BABYLON.Engine = Engine;
  12312. })(BABYLON || (BABYLON = {}));
  12313. //# sourceMappingURL=babylon.engine.js.map
  12314. var BABYLON;
  12315. (function (BABYLON) {
  12316. /**
  12317. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12318. */
  12319. var Node = /** @class */ (function () {
  12320. /**
  12321. * @constructor
  12322. * @param {string} name - the name and id to be given to this node
  12323. * @param {BABYLON.Scene} the scene this node will be added to
  12324. */
  12325. function Node(name, scene) {
  12326. if (scene === void 0) { scene = null; }
  12327. this.state = "";
  12328. this.metadata = null;
  12329. this.doNotSerialize = false;
  12330. this.animations = new Array();
  12331. this._ranges = {};
  12332. this._isEnabled = true;
  12333. this._isReady = true;
  12334. this._currentRenderId = -1;
  12335. this._parentRenderId = -1;
  12336. /**
  12337. * An event triggered when the mesh is disposed.
  12338. * @type {BABYLON.Observable}
  12339. */
  12340. this.onDisposeObservable = new BABYLON.Observable();
  12341. // Behaviors
  12342. this._behaviors = new Array();
  12343. this.name = name;
  12344. this.id = name;
  12345. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12346. this.uniqueId = this._scene.getUniqueId();
  12347. this._initCache();
  12348. }
  12349. Object.defineProperty(Node.prototype, "parent", {
  12350. get: function () {
  12351. return this._parentNode;
  12352. },
  12353. set: function (parent) {
  12354. if (this._parentNode === parent) {
  12355. return;
  12356. }
  12357. if (this._parentNode) {
  12358. var index = this._parentNode._children.indexOf(this);
  12359. if (index !== -1) {
  12360. this._parentNode._children.splice(index, 1);
  12361. }
  12362. }
  12363. this._parentNode = parent;
  12364. if (this._parentNode) {
  12365. if (!this._parentNode._children) {
  12366. this._parentNode._children = new Array();
  12367. }
  12368. this._parentNode._children.push(this);
  12369. }
  12370. },
  12371. enumerable: true,
  12372. configurable: true
  12373. });
  12374. Node.prototype.getClassName = function () {
  12375. return "Node";
  12376. };
  12377. Object.defineProperty(Node.prototype, "onDispose", {
  12378. set: function (callback) {
  12379. if (this._onDisposeObserver) {
  12380. this.onDisposeObservable.remove(this._onDisposeObserver);
  12381. }
  12382. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12383. },
  12384. enumerable: true,
  12385. configurable: true
  12386. });
  12387. Node.prototype.getScene = function () {
  12388. return this._scene;
  12389. };
  12390. Node.prototype.getEngine = function () {
  12391. return this._scene.getEngine();
  12392. };
  12393. Node.prototype.addBehavior = function (behavior) {
  12394. var _this = this;
  12395. var index = this._behaviors.indexOf(behavior);
  12396. if (index !== -1) {
  12397. return this;
  12398. }
  12399. behavior.init();
  12400. if (this._scene.isLoading) {
  12401. // We defer the attach when the scene will be loaded
  12402. var observer = this._scene.onDataLoadedObservable.add(function () {
  12403. behavior.attach(_this);
  12404. _this._scene.onDataLoadedObservable.remove(observer);
  12405. });
  12406. }
  12407. else {
  12408. behavior.attach(this);
  12409. }
  12410. this._behaviors.push(behavior);
  12411. return this;
  12412. };
  12413. Node.prototype.removeBehavior = function (behavior) {
  12414. var index = this._behaviors.indexOf(behavior);
  12415. if (index === -1) {
  12416. return this;
  12417. }
  12418. this._behaviors[index].detach();
  12419. this._behaviors.splice(index, 1);
  12420. return this;
  12421. };
  12422. Object.defineProperty(Node.prototype, "behaviors", {
  12423. get: function () {
  12424. return this._behaviors;
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Node.prototype.getBehaviorByName = function (name) {
  12430. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12431. var behavior = _a[_i];
  12432. if (behavior.name === name) {
  12433. return behavior;
  12434. }
  12435. }
  12436. return null;
  12437. };
  12438. // override it in derived class
  12439. Node.prototype.getWorldMatrix = function () {
  12440. return BABYLON.Matrix.Identity();
  12441. };
  12442. // override it in derived class if you add new variables to the cache
  12443. // and call the parent class method
  12444. Node.prototype._initCache = function () {
  12445. this._cache = {};
  12446. this._cache.parent = undefined;
  12447. };
  12448. Node.prototype.updateCache = function (force) {
  12449. if (!force && this.isSynchronized())
  12450. return;
  12451. this._cache.parent = this.parent;
  12452. this._updateCache();
  12453. };
  12454. // override it in derived class if you add new variables to the cache
  12455. // and call the parent class method if !ignoreParentClass
  12456. Node.prototype._updateCache = function (ignoreParentClass) {
  12457. };
  12458. // override it in derived class if you add new variables to the cache
  12459. Node.prototype._isSynchronized = function () {
  12460. return true;
  12461. };
  12462. Node.prototype._markSyncedWithParent = function () {
  12463. if (this.parent) {
  12464. this._parentRenderId = this.parent._currentRenderId;
  12465. }
  12466. };
  12467. Node.prototype.isSynchronizedWithParent = function () {
  12468. if (!this.parent) {
  12469. return true;
  12470. }
  12471. if (this._parentRenderId !== this.parent._currentRenderId) {
  12472. return false;
  12473. }
  12474. return this.parent.isSynchronized();
  12475. };
  12476. Node.prototype.isSynchronized = function (updateCache) {
  12477. var check = this.hasNewParent();
  12478. check = check || !this.isSynchronizedWithParent();
  12479. check = check || !this._isSynchronized();
  12480. if (updateCache)
  12481. this.updateCache(true);
  12482. return !check;
  12483. };
  12484. Node.prototype.hasNewParent = function (update) {
  12485. if (this._cache.parent === this.parent)
  12486. return false;
  12487. if (update)
  12488. this._cache.parent = this.parent;
  12489. return true;
  12490. };
  12491. /**
  12492. * Is this node ready to be used/rendered
  12493. * @return {boolean} is it ready
  12494. */
  12495. Node.prototype.isReady = function () {
  12496. return this._isReady;
  12497. };
  12498. /**
  12499. * Is this node enabled.
  12500. * If the node has a parent and is enabled, the parent will be inspected as well.
  12501. * @return {boolean} whether this node (and its parent) is enabled.
  12502. * @see setEnabled
  12503. */
  12504. Node.prototype.isEnabled = function () {
  12505. if (!this._isEnabled) {
  12506. return false;
  12507. }
  12508. if (this.parent) {
  12509. return this.parent.isEnabled();
  12510. }
  12511. return true;
  12512. };
  12513. /**
  12514. * Set the enabled state of this node.
  12515. * @param {boolean} value - the new enabled state
  12516. * @see isEnabled
  12517. */
  12518. Node.prototype.setEnabled = function (value) {
  12519. this._isEnabled = value;
  12520. };
  12521. /**
  12522. * Is this node a descendant of the given node.
  12523. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12524. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12525. * @see parent
  12526. */
  12527. Node.prototype.isDescendantOf = function (ancestor) {
  12528. if (this.parent) {
  12529. if (this.parent === ancestor) {
  12530. return true;
  12531. }
  12532. return this.parent.isDescendantOf(ancestor);
  12533. }
  12534. return false;
  12535. };
  12536. /**
  12537. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12538. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12539. * @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.
  12540. * @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.
  12541. */
  12542. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12543. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12544. if (!this._children) {
  12545. return;
  12546. }
  12547. for (var index = 0; index < this._children.length; index++) {
  12548. var item = this._children[index];
  12549. if (!predicate || predicate(item)) {
  12550. results.push(item);
  12551. }
  12552. if (!directDescendantsOnly) {
  12553. item._getDescendants(results, false, predicate);
  12554. }
  12555. }
  12556. };
  12557. /**
  12558. * Will return all nodes that have this node as ascendant.
  12559. * @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.
  12560. * @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.
  12561. * @return {BABYLON.Node[]} all children nodes of all types.
  12562. */
  12563. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12564. var results = new Array();
  12565. this._getDescendants(results, directDescendantsOnly, predicate);
  12566. return results;
  12567. };
  12568. /**
  12569. * Get all child-meshes of this node.
  12570. */
  12571. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12572. var results = [];
  12573. this._getDescendants(results, directDescendantsOnly, function (node) {
  12574. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12575. });
  12576. return results;
  12577. };
  12578. /**
  12579. * Get all child-transformNodes of this node.
  12580. */
  12581. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12582. var results = [];
  12583. this._getDescendants(results, directDescendantsOnly, function (node) {
  12584. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12585. });
  12586. return results;
  12587. };
  12588. /**
  12589. * Get all direct children of this node.
  12590. */
  12591. Node.prototype.getChildren = function (predicate) {
  12592. return this.getDescendants(true, predicate);
  12593. };
  12594. Node.prototype._setReady = function (state) {
  12595. if (state === this._isReady) {
  12596. return;
  12597. }
  12598. if (!state) {
  12599. this._isReady = false;
  12600. return;
  12601. }
  12602. this._isReady = true;
  12603. if (this.onReady) {
  12604. this.onReady(this);
  12605. }
  12606. };
  12607. Node.prototype.getAnimationByName = function (name) {
  12608. for (var i = 0; i < this.animations.length; i++) {
  12609. var animation = this.animations[i];
  12610. if (animation.name === name) {
  12611. return animation;
  12612. }
  12613. }
  12614. return null;
  12615. };
  12616. Node.prototype.createAnimationRange = function (name, from, to) {
  12617. // check name not already in use
  12618. if (!this._ranges[name]) {
  12619. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12620. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12621. if (this.animations[i]) {
  12622. this.animations[i].createRange(name, from, to);
  12623. }
  12624. }
  12625. }
  12626. };
  12627. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12628. if (deleteFrames === void 0) { deleteFrames = true; }
  12629. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12630. if (this.animations[i]) {
  12631. this.animations[i].deleteRange(name, deleteFrames);
  12632. }
  12633. }
  12634. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12635. };
  12636. Node.prototype.getAnimationRange = function (name) {
  12637. return this._ranges[name];
  12638. };
  12639. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12640. var range = this.getAnimationRange(name);
  12641. if (!range) {
  12642. return;
  12643. }
  12644. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12645. };
  12646. Node.prototype.serializeAnimationRanges = function () {
  12647. var serializationRanges = [];
  12648. for (var name in this._ranges) {
  12649. var localRange = this._ranges[name];
  12650. if (!localRange) {
  12651. continue;
  12652. }
  12653. var range = {};
  12654. range.name = name;
  12655. range.from = localRange.from;
  12656. range.to = localRange.to;
  12657. serializationRanges.push(range);
  12658. }
  12659. return serializationRanges;
  12660. };
  12661. Node.prototype.dispose = function () {
  12662. this.parent = null;
  12663. // Callback
  12664. this.onDisposeObservable.notifyObservers(this);
  12665. this.onDisposeObservable.clear();
  12666. // Behaviors
  12667. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12668. var behavior = _a[_i];
  12669. behavior.detach();
  12670. }
  12671. this._behaviors = [];
  12672. };
  12673. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12674. if (parsedNode.ranges) {
  12675. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12676. var data = parsedNode.ranges[index];
  12677. node.createAnimationRange(data.name, data.from, data.to);
  12678. }
  12679. }
  12680. };
  12681. __decorate([
  12682. BABYLON.serialize()
  12683. ], Node.prototype, "name", void 0);
  12684. __decorate([
  12685. BABYLON.serialize()
  12686. ], Node.prototype, "id", void 0);
  12687. __decorate([
  12688. BABYLON.serialize()
  12689. ], Node.prototype, "uniqueId", void 0);
  12690. __decorate([
  12691. BABYLON.serialize()
  12692. ], Node.prototype, "state", void 0);
  12693. __decorate([
  12694. BABYLON.serialize()
  12695. ], Node.prototype, "metadata", void 0);
  12696. return Node;
  12697. }());
  12698. BABYLON.Node = Node;
  12699. })(BABYLON || (BABYLON = {}));
  12700. //# sourceMappingURL=babylon.node.js.map
  12701. var BABYLON;
  12702. (function (BABYLON) {
  12703. var BoundingSphere = /** @class */ (function () {
  12704. function BoundingSphere(minimum, maximum) {
  12705. this.minimum = minimum;
  12706. this.maximum = maximum;
  12707. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12708. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12709. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12710. this.radius = distance * 0.5;
  12711. this.centerWorld = BABYLON.Vector3.Zero();
  12712. this._update(BABYLON.Matrix.Identity());
  12713. }
  12714. // Methods
  12715. BoundingSphere.prototype._update = function (world) {
  12716. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12717. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12718. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12719. };
  12720. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12721. for (var i = 0; i < 6; i++) {
  12722. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12723. return false;
  12724. }
  12725. return true;
  12726. };
  12727. BoundingSphere.prototype.intersectsPoint = function (point) {
  12728. var x = this.centerWorld.x - point.x;
  12729. var y = this.centerWorld.y - point.y;
  12730. var z = this.centerWorld.z - point.z;
  12731. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12732. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12733. return false;
  12734. return true;
  12735. };
  12736. // Statics
  12737. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12738. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12739. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12740. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12741. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12742. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12743. return false;
  12744. return true;
  12745. };
  12746. return BoundingSphere;
  12747. }());
  12748. BABYLON.BoundingSphere = BoundingSphere;
  12749. })(BABYLON || (BABYLON = {}));
  12750. //# sourceMappingURL=babylon.boundingSphere.js.map
  12751. var BABYLON;
  12752. (function (BABYLON) {
  12753. var BoundingBox = /** @class */ (function () {
  12754. function BoundingBox(minimum, maximum) {
  12755. this.minimum = minimum;
  12756. this.maximum = maximum;
  12757. this.vectors = new Array();
  12758. this.vectorsWorld = new Array();
  12759. // Bounding vectors
  12760. this.vectors.push(this.minimum.clone());
  12761. this.vectors.push(this.maximum.clone());
  12762. this.vectors.push(this.minimum.clone());
  12763. this.vectors[2].x = this.maximum.x;
  12764. this.vectors.push(this.minimum.clone());
  12765. this.vectors[3].y = this.maximum.y;
  12766. this.vectors.push(this.minimum.clone());
  12767. this.vectors[4].z = this.maximum.z;
  12768. this.vectors.push(this.maximum.clone());
  12769. this.vectors[5].z = this.minimum.z;
  12770. this.vectors.push(this.maximum.clone());
  12771. this.vectors[6].x = this.minimum.x;
  12772. this.vectors.push(this.maximum.clone());
  12773. this.vectors[7].y = this.minimum.y;
  12774. // OBB
  12775. this.center = this.maximum.add(this.minimum).scale(0.5);
  12776. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12777. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12778. // World
  12779. for (var index = 0; index < this.vectors.length; index++) {
  12780. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12781. }
  12782. this.minimumWorld = BABYLON.Vector3.Zero();
  12783. this.maximumWorld = BABYLON.Vector3.Zero();
  12784. this.centerWorld = BABYLON.Vector3.Zero();
  12785. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12786. this._update(BABYLON.Matrix.Identity());
  12787. }
  12788. // Methods
  12789. BoundingBox.prototype.getWorldMatrix = function () {
  12790. return this._worldMatrix;
  12791. };
  12792. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12793. this._worldMatrix.copyFrom(matrix);
  12794. return this;
  12795. };
  12796. BoundingBox.prototype._update = function (world) {
  12797. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12798. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12799. for (var index = 0; index < this.vectors.length; index++) {
  12800. var v = this.vectorsWorld[index];
  12801. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12802. if (v.x < this.minimumWorld.x)
  12803. this.minimumWorld.x = v.x;
  12804. if (v.y < this.minimumWorld.y)
  12805. this.minimumWorld.y = v.y;
  12806. if (v.z < this.minimumWorld.z)
  12807. this.minimumWorld.z = v.z;
  12808. if (v.x > this.maximumWorld.x)
  12809. this.maximumWorld.x = v.x;
  12810. if (v.y > this.maximumWorld.y)
  12811. this.maximumWorld.y = v.y;
  12812. if (v.z > this.maximumWorld.z)
  12813. this.maximumWorld.z = v.z;
  12814. }
  12815. // Extend
  12816. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12817. this.extendSizeWorld.scaleInPlace(0.5);
  12818. // OBB
  12819. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12820. this.centerWorld.scaleInPlace(0.5);
  12821. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12822. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12823. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12824. this._worldMatrix = world;
  12825. };
  12826. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12827. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12828. };
  12829. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12830. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12831. };
  12832. BoundingBox.prototype.intersectsPoint = function (point) {
  12833. var delta = -BABYLON.Epsilon;
  12834. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12835. return false;
  12836. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12837. return false;
  12838. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12839. return false;
  12840. return true;
  12841. };
  12842. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12843. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12844. };
  12845. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12846. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12847. return false;
  12848. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12849. return false;
  12850. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12851. return false;
  12852. return true;
  12853. };
  12854. // Statics
  12855. BoundingBox.Intersects = function (box0, box1) {
  12856. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12857. return false;
  12858. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12859. return false;
  12860. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12861. return false;
  12862. return true;
  12863. };
  12864. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12865. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12866. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12867. return (num <= (sphereRadius * sphereRadius));
  12868. };
  12869. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12870. for (var p = 0; p < 6; p++) {
  12871. for (var i = 0; i < 8; i++) {
  12872. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12873. return false;
  12874. }
  12875. }
  12876. }
  12877. return true;
  12878. };
  12879. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12880. for (var p = 0; p < 6; p++) {
  12881. var inCount = 8;
  12882. for (var i = 0; i < 8; i++) {
  12883. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12884. --inCount;
  12885. }
  12886. else {
  12887. break;
  12888. }
  12889. }
  12890. if (inCount === 0)
  12891. return false;
  12892. }
  12893. return true;
  12894. };
  12895. return BoundingBox;
  12896. }());
  12897. BABYLON.BoundingBox = BoundingBox;
  12898. })(BABYLON || (BABYLON = {}));
  12899. //# sourceMappingURL=babylon.boundingBox.js.map
  12900. var BABYLON;
  12901. (function (BABYLON) {
  12902. var computeBoxExtents = function (axis, box) {
  12903. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12904. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12905. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12906. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12907. var r = r0 + r1 + r2;
  12908. return {
  12909. min: p - r,
  12910. max: p + r
  12911. };
  12912. };
  12913. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12914. var axisOverlap = function (axis, box0, box1) {
  12915. var result0 = computeBoxExtents(axis, box0);
  12916. var result1 = computeBoxExtents(axis, box1);
  12917. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12918. };
  12919. var BoundingInfo = /** @class */ (function () {
  12920. function BoundingInfo(minimum, maximum) {
  12921. this.minimum = minimum;
  12922. this.maximum = maximum;
  12923. this._isLocked = false;
  12924. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12925. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12926. }
  12927. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12928. get: function () {
  12929. return this._isLocked;
  12930. },
  12931. set: function (value) {
  12932. this._isLocked = value;
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. // Methods
  12938. BoundingInfo.prototype.update = function (world) {
  12939. if (this._isLocked) {
  12940. return;
  12941. }
  12942. this.boundingBox._update(world);
  12943. this.boundingSphere._update(world);
  12944. };
  12945. /**
  12946. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12947. * @param center New center of the bounding info
  12948. * @param extend New extend of the bounding info
  12949. */
  12950. BoundingInfo.prototype.centerOn = function (center, extend) {
  12951. this.minimum = center.subtract(extend);
  12952. this.maximum = center.add(extend);
  12953. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12954. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12955. return this;
  12956. };
  12957. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12958. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12959. return false;
  12960. return this.boundingBox.isInFrustum(frustumPlanes);
  12961. };
  12962. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12963. /**
  12964. * Gets the world distance between the min and max points of the bounding box
  12965. */
  12966. get: function () {
  12967. var boundingBox = this.boundingBox;
  12968. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12969. return size.length();
  12970. },
  12971. enumerable: true,
  12972. configurable: true
  12973. });
  12974. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12975. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12976. };
  12977. BoundingInfo.prototype._checkCollision = function (collider) {
  12978. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12979. };
  12980. BoundingInfo.prototype.intersectsPoint = function (point) {
  12981. if (!this.boundingSphere.centerWorld) {
  12982. return false;
  12983. }
  12984. if (!this.boundingSphere.intersectsPoint(point)) {
  12985. return false;
  12986. }
  12987. if (!this.boundingBox.intersectsPoint(point)) {
  12988. return false;
  12989. }
  12990. return true;
  12991. };
  12992. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12993. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12994. return false;
  12995. }
  12996. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12997. return false;
  12998. }
  12999. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13000. return false;
  13001. }
  13002. if (!precise) {
  13003. return true;
  13004. }
  13005. var box0 = this.boundingBox;
  13006. var box1 = boundingInfo.boundingBox;
  13007. if (!axisOverlap(box0.directions[0], box0, box1))
  13008. return false;
  13009. if (!axisOverlap(box0.directions[1], box0, box1))
  13010. return false;
  13011. if (!axisOverlap(box0.directions[2], box0, box1))
  13012. return false;
  13013. if (!axisOverlap(box1.directions[0], box0, box1))
  13014. return false;
  13015. if (!axisOverlap(box1.directions[1], box0, box1))
  13016. return false;
  13017. if (!axisOverlap(box1.directions[2], box0, box1))
  13018. return false;
  13019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13020. return false;
  13021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13022. return false;
  13023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13024. return false;
  13025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13026. return false;
  13027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13028. return false;
  13029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13030. return false;
  13031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13032. return false;
  13033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13034. return false;
  13035. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13036. return false;
  13037. return true;
  13038. };
  13039. return BoundingInfo;
  13040. }());
  13041. BABYLON.BoundingInfo = BoundingInfo;
  13042. })(BABYLON || (BABYLON = {}));
  13043. //# sourceMappingURL=babylon.boundingInfo.js.map
  13044. var BABYLON;
  13045. (function (BABYLON) {
  13046. var TransformNode = /** @class */ (function (_super) {
  13047. __extends(TransformNode, _super);
  13048. function TransformNode(name, scene, isPure) {
  13049. if (scene === void 0) { scene = null; }
  13050. if (isPure === void 0) { isPure = true; }
  13051. var _this = _super.call(this, name, scene) || this;
  13052. // Properties
  13053. _this._rotation = BABYLON.Vector3.Zero();
  13054. _this._scaling = BABYLON.Vector3.One();
  13055. _this._isDirty = false;
  13056. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13057. _this.scalingDeterminant = 1;
  13058. _this.infiniteDistance = false;
  13059. _this.position = BABYLON.Vector3.Zero();
  13060. _this._localWorld = BABYLON.Matrix.Zero();
  13061. _this._worldMatrix = BABYLON.Matrix.Zero();
  13062. _this._absolutePosition = BABYLON.Vector3.Zero();
  13063. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13064. _this._postMultiplyPivotMatrix = false;
  13065. _this._isWorldMatrixFrozen = false;
  13066. /**
  13067. * An event triggered after the world matrix is updated
  13068. * @type {BABYLON.Observable}
  13069. */
  13070. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13071. _this._nonUniformScaling = false;
  13072. if (isPure) {
  13073. _this.getScene().addTransformNode(_this);
  13074. }
  13075. return _this;
  13076. }
  13077. Object.defineProperty(TransformNode.prototype, "rotation", {
  13078. /**
  13079. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13080. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13081. * Default : (0.0, 0.0, 0.0)
  13082. */
  13083. get: function () {
  13084. return this._rotation;
  13085. },
  13086. set: function (newRotation) {
  13087. this._rotation = newRotation;
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. Object.defineProperty(TransformNode.prototype, "scaling", {
  13093. /**
  13094. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13095. * Default : (1.0, 1.0, 1.0)
  13096. */
  13097. get: function () {
  13098. return this._scaling;
  13099. },
  13100. /**
  13101. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13102. * Default : (1.0, 1.0, 1.0)
  13103. */
  13104. set: function (newScaling) {
  13105. this._scaling = newScaling;
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13111. /**
  13112. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13113. * It's null by default.
  13114. * 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)
  13115. */
  13116. get: function () {
  13117. return this._rotationQuaternion;
  13118. },
  13119. set: function (quaternion) {
  13120. this._rotationQuaternion = quaternion;
  13121. //reset the rotation vector.
  13122. if (quaternion && this.rotation.length()) {
  13123. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13124. }
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. /**
  13130. * Returns the latest update of the World matrix
  13131. * Returns a Matrix.
  13132. */
  13133. TransformNode.prototype.getWorldMatrix = function () {
  13134. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13135. this.computeWorldMatrix();
  13136. }
  13137. return this._worldMatrix;
  13138. };
  13139. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13140. /**
  13141. * Returns directly the latest state of the mesh World matrix.
  13142. * A Matrix is returned.
  13143. */
  13144. get: function () {
  13145. return this._worldMatrix;
  13146. },
  13147. enumerable: true,
  13148. configurable: true
  13149. });
  13150. /**
  13151. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13152. * Returns the AbstractMesh.
  13153. */
  13154. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13155. this._poseMatrix.copyFrom(matrix);
  13156. return this;
  13157. };
  13158. /**
  13159. * Returns the mesh Pose matrix.
  13160. * Returned object : Matrix
  13161. */
  13162. TransformNode.prototype.getPoseMatrix = function () {
  13163. return this._poseMatrix;
  13164. };
  13165. TransformNode.prototype._isSynchronized = function () {
  13166. if (this._isDirty) {
  13167. return false;
  13168. }
  13169. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13170. return false;
  13171. if (this._cache.pivotMatrixUpdated) {
  13172. return false;
  13173. }
  13174. if (this.infiniteDistance) {
  13175. return false;
  13176. }
  13177. if (!this._cache.position.equals(this.position))
  13178. return false;
  13179. if (this.rotationQuaternion) {
  13180. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13181. return false;
  13182. }
  13183. if (!this._cache.rotation.equals(this.rotation))
  13184. return false;
  13185. if (!this._cache.scaling.equals(this.scaling))
  13186. return false;
  13187. return true;
  13188. };
  13189. TransformNode.prototype._initCache = function () {
  13190. _super.prototype._initCache.call(this);
  13191. this._cache.localMatrixUpdated = false;
  13192. this._cache.position = BABYLON.Vector3.Zero();
  13193. this._cache.scaling = BABYLON.Vector3.Zero();
  13194. this._cache.rotation = BABYLON.Vector3.Zero();
  13195. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13196. this._cache.billboardMode = -1;
  13197. };
  13198. TransformNode.prototype.markAsDirty = function (property) {
  13199. if (property === "rotation") {
  13200. this.rotationQuaternion = null;
  13201. }
  13202. this._currentRenderId = Number.MAX_VALUE;
  13203. this._isDirty = true;
  13204. return this;
  13205. };
  13206. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13207. /**
  13208. * Returns the current mesh absolute position.
  13209. * Retuns a Vector3.
  13210. */
  13211. get: function () {
  13212. return this._absolutePosition;
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. /**
  13218. * Sets a new pivot matrix to the mesh.
  13219. * Returns the AbstractMesh.
  13220. */
  13221. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13222. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13223. this._pivotMatrix = matrix.clone();
  13224. this._cache.pivotMatrixUpdated = true;
  13225. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13226. if (this._postMultiplyPivotMatrix) {
  13227. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13228. }
  13229. return this;
  13230. };
  13231. /**
  13232. * Returns the mesh pivot matrix.
  13233. * Default : Identity.
  13234. * A Matrix is returned.
  13235. */
  13236. TransformNode.prototype.getPivotMatrix = function () {
  13237. return this._pivotMatrix;
  13238. };
  13239. /**
  13240. * Prevents the World matrix to be computed any longer.
  13241. * Returns the AbstractMesh.
  13242. */
  13243. TransformNode.prototype.freezeWorldMatrix = function () {
  13244. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13245. this.computeWorldMatrix(true);
  13246. this._isWorldMatrixFrozen = true;
  13247. return this;
  13248. };
  13249. /**
  13250. * Allows back the World matrix computation.
  13251. * Returns the AbstractMesh.
  13252. */
  13253. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13254. this._isWorldMatrixFrozen = false;
  13255. this.computeWorldMatrix(true);
  13256. return this;
  13257. };
  13258. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13259. /**
  13260. * True if the World matrix has been frozen.
  13261. * Returns a boolean.
  13262. */
  13263. get: function () {
  13264. return this._isWorldMatrixFrozen;
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. /**
  13270. * Retuns the mesh absolute position in the World.
  13271. * Returns a Vector3.
  13272. */
  13273. TransformNode.prototype.getAbsolutePosition = function () {
  13274. this.computeWorldMatrix();
  13275. return this._absolutePosition;
  13276. };
  13277. /**
  13278. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13279. * Returns the AbstractMesh.
  13280. */
  13281. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13282. if (!absolutePosition) {
  13283. return this;
  13284. }
  13285. var absolutePositionX;
  13286. var absolutePositionY;
  13287. var absolutePositionZ;
  13288. if (absolutePosition.x === undefined) {
  13289. if (arguments.length < 3) {
  13290. return this;
  13291. }
  13292. absolutePositionX = arguments[0];
  13293. absolutePositionY = arguments[1];
  13294. absolutePositionZ = arguments[2];
  13295. }
  13296. else {
  13297. absolutePositionX = absolutePosition.x;
  13298. absolutePositionY = absolutePosition.y;
  13299. absolutePositionZ = absolutePosition.z;
  13300. }
  13301. if (this.parent) {
  13302. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13303. invertParentWorldMatrix.invert();
  13304. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13305. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13306. }
  13307. else {
  13308. this.position.x = absolutePositionX;
  13309. this.position.y = absolutePositionY;
  13310. this.position.z = absolutePositionZ;
  13311. }
  13312. return this;
  13313. };
  13314. /**
  13315. * Sets the mesh position in its local space.
  13316. * Returns the AbstractMesh.
  13317. */
  13318. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13319. this.computeWorldMatrix();
  13320. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13321. return this;
  13322. };
  13323. /**
  13324. * Returns the mesh position in the local space from the current World matrix values.
  13325. * Returns a new Vector3.
  13326. */
  13327. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13328. this.computeWorldMatrix();
  13329. var invLocalWorldMatrix = this._localWorld.clone();
  13330. invLocalWorldMatrix.invert();
  13331. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13332. };
  13333. /**
  13334. * Translates the mesh along the passed Vector3 in its local space.
  13335. * Returns the AbstractMesh.
  13336. */
  13337. TransformNode.prototype.locallyTranslate = function (vector3) {
  13338. this.computeWorldMatrix(true);
  13339. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13340. return this;
  13341. };
  13342. /**
  13343. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13344. * @param targetPoint the position (must be in same space as current mesh) to look at
  13345. * @param yawCor optional yaw (y-axis) correction in radians
  13346. * @param pitchCor optional pitch (x-axis) correction in radians
  13347. * @param rollCor optional roll (z-axis) correction in radians
  13348. * @param space the choosen space of the target
  13349. * @returns the TransformNode.
  13350. */
  13351. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13352. if (yawCor === void 0) { yawCor = 0; }
  13353. if (pitchCor === void 0) { pitchCor = 0; }
  13354. if (rollCor === void 0) { rollCor = 0; }
  13355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13356. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13357. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13358. targetPoint.subtractToRef(pos, dv);
  13359. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13360. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13361. var pitch = Math.atan2(dv.y, len);
  13362. if (this.rotationQuaternion) {
  13363. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13364. }
  13365. else {
  13366. this.rotation.x = pitch + pitchCor;
  13367. this.rotation.y = yaw + yawCor;
  13368. this.rotation.z = rollCor;
  13369. }
  13370. return this;
  13371. };
  13372. /**
  13373. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13374. * This Vector3 is expressed in the World space.
  13375. */
  13376. TransformNode.prototype.getDirection = function (localAxis) {
  13377. var result = BABYLON.Vector3.Zero();
  13378. this.getDirectionToRef(localAxis, result);
  13379. return result;
  13380. };
  13381. /**
  13382. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13383. * localAxis is expressed in the mesh local space.
  13384. * result is computed in the Wordl space from the mesh World matrix.
  13385. * Returns the AbstractMesh.
  13386. */
  13387. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13388. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13389. return this;
  13390. };
  13391. TransformNode.prototype.setPivotPoint = function (point, space) {
  13392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13393. if (this.getScene().getRenderId() == 0) {
  13394. this.computeWorldMatrix(true);
  13395. }
  13396. var wm = this.getWorldMatrix();
  13397. if (space == BABYLON.Space.WORLD) {
  13398. var tmat = BABYLON.Tmp.Matrix[0];
  13399. wm.invertToRef(tmat);
  13400. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13401. }
  13402. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13403. this._pivotMatrix.m[12] = -point.x;
  13404. this._pivotMatrix.m[13] = -point.y;
  13405. this._pivotMatrix.m[14] = -point.z;
  13406. this._cache.pivotMatrixUpdated = true;
  13407. return this;
  13408. };
  13409. /**
  13410. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13411. */
  13412. TransformNode.prototype.getPivotPoint = function () {
  13413. var point = BABYLON.Vector3.Zero();
  13414. this.getPivotPointToRef(point);
  13415. return point;
  13416. };
  13417. /**
  13418. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13419. * Returns the AbstractMesh.
  13420. */
  13421. TransformNode.prototype.getPivotPointToRef = function (result) {
  13422. result.x = -this._pivotMatrix.m[12];
  13423. result.y = -this._pivotMatrix.m[13];
  13424. result.z = -this._pivotMatrix.m[14];
  13425. return this;
  13426. };
  13427. /**
  13428. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13429. */
  13430. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13431. var point = BABYLON.Vector3.Zero();
  13432. this.getAbsolutePivotPointToRef(point);
  13433. return point;
  13434. };
  13435. /**
  13436. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13437. * Returns the AbstractMesh.
  13438. */
  13439. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13440. result.x = this._pivotMatrix.m[12];
  13441. result.y = this._pivotMatrix.m[13];
  13442. result.z = this._pivotMatrix.m[14];
  13443. this.getPivotPointToRef(result);
  13444. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13445. return this;
  13446. };
  13447. /**
  13448. * Defines the passed node as the parent of the current node.
  13449. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13450. * Returns the TransformNode.
  13451. */
  13452. TransformNode.prototype.setParent = function (node) {
  13453. if (node == null) {
  13454. var rotation = BABYLON.Tmp.Quaternion[0];
  13455. var position = BABYLON.Tmp.Vector3[0];
  13456. var scale = BABYLON.Tmp.Vector3[1];
  13457. if (this.parent && this.parent.computeWorldMatrix) {
  13458. this.parent.computeWorldMatrix(true);
  13459. }
  13460. this.computeWorldMatrix(true);
  13461. this.getWorldMatrix().decompose(scale, rotation, position);
  13462. if (this.rotationQuaternion) {
  13463. this.rotationQuaternion.copyFrom(rotation);
  13464. }
  13465. else {
  13466. rotation.toEulerAnglesToRef(this.rotation);
  13467. }
  13468. this.scaling.x = scale.x;
  13469. this.scaling.y = scale.y;
  13470. this.scaling.z = scale.z;
  13471. this.position.x = position.x;
  13472. this.position.y = position.y;
  13473. this.position.z = position.z;
  13474. }
  13475. else {
  13476. var rotation = BABYLON.Tmp.Quaternion[0];
  13477. var position = BABYLON.Tmp.Vector3[0];
  13478. var scale = BABYLON.Tmp.Vector3[1];
  13479. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13480. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13481. this.computeWorldMatrix(true);
  13482. node.computeWorldMatrix(true);
  13483. node.getWorldMatrix().invertToRef(invParentMatrix);
  13484. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13485. diffMatrix.decompose(scale, rotation, position);
  13486. if (this.rotationQuaternion) {
  13487. this.rotationQuaternion.copyFrom(rotation);
  13488. }
  13489. else {
  13490. rotation.toEulerAnglesToRef(this.rotation);
  13491. }
  13492. this.position.x = position.x;
  13493. this.position.y = position.y;
  13494. this.position.z = position.z;
  13495. this.scaling.x = scale.x;
  13496. this.scaling.y = scale.y;
  13497. this.scaling.z = scale.z;
  13498. }
  13499. this.parent = node;
  13500. return this;
  13501. };
  13502. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13503. get: function () {
  13504. return this._nonUniformScaling;
  13505. },
  13506. enumerable: true,
  13507. configurable: true
  13508. });
  13509. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13510. if (this._nonUniformScaling === value) {
  13511. return false;
  13512. }
  13513. this._nonUniformScaling = true;
  13514. return true;
  13515. };
  13516. /**
  13517. * Attach the current TransformNode to another TransformNode associated with a bone
  13518. * @param bone Bone affecting the TransformNode
  13519. * @param affectedTransformNode TransformNode associated with the bone
  13520. */
  13521. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13522. this._transformToBoneReferal = affectedTransformNode;
  13523. this.parent = bone;
  13524. if (bone.getWorldMatrix().determinant() < 0) {
  13525. this.scalingDeterminant *= -1;
  13526. }
  13527. return this;
  13528. };
  13529. TransformNode.prototype.detachFromBone = function () {
  13530. if (!this.parent) {
  13531. return this;
  13532. }
  13533. if (this.parent.getWorldMatrix().determinant() < 0) {
  13534. this.scalingDeterminant *= -1;
  13535. }
  13536. this._transformToBoneReferal = null;
  13537. this.parent = null;
  13538. return this;
  13539. };
  13540. /**
  13541. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13542. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13543. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13544. * The passed axis is also normalized.
  13545. * Returns the AbstractMesh.
  13546. */
  13547. TransformNode.prototype.rotate = function (axis, amount, space) {
  13548. axis.normalize();
  13549. if (!this.rotationQuaternion) {
  13550. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13551. this.rotation = BABYLON.Vector3.Zero();
  13552. }
  13553. var rotationQuaternion;
  13554. if (!space || space === BABYLON.Space.LOCAL) {
  13555. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13556. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13557. }
  13558. else {
  13559. if (this.parent) {
  13560. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13561. invertParentWorldMatrix.invert();
  13562. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13563. }
  13564. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13565. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13566. }
  13567. return this;
  13568. };
  13569. /**
  13570. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13571. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13572. * The passed axis is also normalized.
  13573. * Returns the AbstractMesh.
  13574. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13575. */
  13576. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13577. axis.normalize();
  13578. if (!this.rotationQuaternion) {
  13579. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13580. this.rotation.copyFromFloats(0, 0, 0);
  13581. }
  13582. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13583. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13584. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13585. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13586. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13587. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13588. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13589. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13590. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13591. return this;
  13592. };
  13593. /**
  13594. * Translates the mesh along the axis vector for the passed distance in the given space.
  13595. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13596. * Returns the AbstractMesh.
  13597. */
  13598. TransformNode.prototype.translate = function (axis, distance, space) {
  13599. var displacementVector = axis.scale(distance);
  13600. if (!space || space === BABYLON.Space.LOCAL) {
  13601. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13602. this.setPositionWithLocalVector(tempV3);
  13603. }
  13604. else {
  13605. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13606. }
  13607. return this;
  13608. };
  13609. /**
  13610. * Adds a rotation step to the mesh current rotation.
  13611. * x, y, z are Euler angles expressed in radians.
  13612. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13613. * This means this rotation is made in the mesh local space only.
  13614. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13615. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13616. * ```javascript
  13617. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13618. * ```
  13619. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13620. * 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.
  13621. * Returns the AbstractMesh.
  13622. */
  13623. TransformNode.prototype.addRotation = function (x, y, z) {
  13624. var rotationQuaternion;
  13625. if (this.rotationQuaternion) {
  13626. rotationQuaternion = this.rotationQuaternion;
  13627. }
  13628. else {
  13629. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13630. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13631. }
  13632. var accumulation = BABYLON.Tmp.Quaternion[0];
  13633. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13634. rotationQuaternion.multiplyInPlace(accumulation);
  13635. if (!this.rotationQuaternion) {
  13636. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13637. }
  13638. return this;
  13639. };
  13640. /**
  13641. * Computes the mesh World matrix and returns it.
  13642. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13643. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13644. * If the parameter `force`is set to `true`, the actual computation is done.
  13645. * Returns the mesh World Matrix.
  13646. */
  13647. TransformNode.prototype.computeWorldMatrix = function (force) {
  13648. if (this._isWorldMatrixFrozen) {
  13649. return this._worldMatrix;
  13650. }
  13651. if (!force && this.isSynchronized(true)) {
  13652. return this._worldMatrix;
  13653. }
  13654. this._cache.position.copyFrom(this.position);
  13655. this._cache.scaling.copyFrom(this.scaling);
  13656. this._cache.pivotMatrixUpdated = false;
  13657. this._cache.billboardMode = this.billboardMode;
  13658. this._currentRenderId = this.getScene().getRenderId();
  13659. this._isDirty = false;
  13660. // Scaling
  13661. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13662. // Rotation
  13663. //rotate, if quaternion is set and rotation was used
  13664. if (this.rotationQuaternion) {
  13665. var len = this.rotation.length();
  13666. if (len) {
  13667. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13668. this.rotation.copyFromFloats(0, 0, 0);
  13669. }
  13670. }
  13671. if (this.rotationQuaternion) {
  13672. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13673. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13674. }
  13675. else {
  13676. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13677. this._cache.rotation.copyFrom(this.rotation);
  13678. }
  13679. // Translation
  13680. var camera = this.getScene().activeCamera;
  13681. if (this.infiniteDistance && !this.parent && camera) {
  13682. var cameraWorldMatrix = camera.getWorldMatrix();
  13683. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13684. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13685. }
  13686. else {
  13687. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13688. }
  13689. // Composing transformations
  13690. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13691. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13692. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13693. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13694. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13695. // Need to decompose each rotation here
  13696. var currentPosition = BABYLON.Tmp.Vector3[3];
  13697. if (this.parent && this.parent.getWorldMatrix) {
  13698. if (this._transformToBoneReferal) {
  13699. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13700. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13701. }
  13702. else {
  13703. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13704. }
  13705. }
  13706. else {
  13707. currentPosition.copyFrom(this.position);
  13708. }
  13709. currentPosition.subtractInPlace(camera.globalPosition);
  13710. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13711. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13712. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13713. }
  13714. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13715. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13716. }
  13717. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13718. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13719. }
  13720. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13721. }
  13722. else {
  13723. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13724. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13725. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13726. }
  13727. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13728. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13729. }
  13730. // Local world
  13731. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13732. // Parent
  13733. if (this.parent && this.parent.getWorldMatrix) {
  13734. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13735. if (this._transformToBoneReferal) {
  13736. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13737. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13738. }
  13739. else {
  13740. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13741. }
  13742. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13743. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13744. this._worldMatrix.copyFrom(this._localWorld);
  13745. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13746. }
  13747. else {
  13748. if (this._transformToBoneReferal) {
  13749. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13750. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13751. }
  13752. else {
  13753. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13754. }
  13755. }
  13756. this._markSyncedWithParent();
  13757. }
  13758. else {
  13759. this._worldMatrix.copyFrom(this._localWorld);
  13760. }
  13761. // Post multiply inverse of pivotMatrix
  13762. if (this._postMultiplyPivotMatrix) {
  13763. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13764. }
  13765. // Normal matrix
  13766. if (this.scaling.isNonUniform) {
  13767. this._updateNonUniformScalingState(true);
  13768. }
  13769. else if (this.parent && this.parent._nonUniformScaling) {
  13770. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13771. }
  13772. else {
  13773. this._updateNonUniformScalingState(false);
  13774. }
  13775. this._afterComputeWorldMatrix();
  13776. // Absolute position
  13777. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13778. // Callbacks
  13779. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13780. if (!this._poseMatrix) {
  13781. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13782. }
  13783. return this._worldMatrix;
  13784. };
  13785. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13786. };
  13787. /**
  13788. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13789. * @param func: callback function to add
  13790. *
  13791. * Returns the TransformNode.
  13792. */
  13793. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13794. this.onAfterWorldMatrixUpdateObservable.add(func);
  13795. return this;
  13796. };
  13797. /**
  13798. * Removes a registered callback function.
  13799. * Returns the TransformNode.
  13800. */
  13801. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13802. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13803. return this;
  13804. };
  13805. /**
  13806. * Clone the current transform node
  13807. * Returns the new transform node
  13808. * @param name Name of the new clone
  13809. * @param newParent New parent for the clone
  13810. * @param doNotCloneChildren Do not clone children hierarchy
  13811. */
  13812. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13813. var _this = this;
  13814. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13815. result.name = name;
  13816. result.id = name;
  13817. if (newParent) {
  13818. result.parent = newParent;
  13819. }
  13820. if (!doNotCloneChildren) {
  13821. // Children
  13822. var directDescendants = this.getDescendants(true);
  13823. for (var index = 0; index < directDescendants.length; index++) {
  13824. var child = directDescendants[index];
  13825. if (child.clone) {
  13826. child.clone(name + "." + child.name, result);
  13827. }
  13828. }
  13829. }
  13830. return result;
  13831. };
  13832. TransformNode.prototype.serialize = function (currentSerializationObject) {
  13833. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  13834. serializationObject.type = this.getClassName();
  13835. // Parent
  13836. if (this.parent) {
  13837. serializationObject.parentId = this.parent.id;
  13838. }
  13839. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13840. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13841. }
  13842. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13843. serializationObject.isEnabled = this.isEnabled();
  13844. // Parent
  13845. if (this.parent) {
  13846. serializationObject.parentId = this.parent.id;
  13847. }
  13848. return serializationObject;
  13849. };
  13850. // Statics
  13851. /**
  13852. * Returns a new TransformNode object parsed from the source provided.
  13853. * The parameter `parsedMesh` is the source.
  13854. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13855. */
  13856. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13857. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  13858. if (BABYLON.Tags) {
  13859. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13860. }
  13861. if (parsedTransformNode.localMatrix) {
  13862. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13863. }
  13864. else if (parsedTransformNode.pivotMatrix) {
  13865. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13866. }
  13867. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13868. // Parent
  13869. if (parsedTransformNode.parentId) {
  13870. transformNode._waitingParentId = parsedTransformNode.parentId;
  13871. }
  13872. return transformNode;
  13873. };
  13874. /**
  13875. * Disposes the TransformNode.
  13876. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13877. * Returns nothing.
  13878. */
  13879. TransformNode.prototype.dispose = function (doNotRecurse) {
  13880. // Animations
  13881. this.getScene().stopAnimation(this);
  13882. // Remove from scene
  13883. this.getScene().removeTransformNode(this);
  13884. this._cache = null;
  13885. if (!doNotRecurse) {
  13886. // Children
  13887. var objects = this.getDescendants(true);
  13888. for (var index = 0; index < objects.length; index++) {
  13889. objects[index].dispose();
  13890. }
  13891. }
  13892. else {
  13893. var childMeshes = this.getChildMeshes(true);
  13894. for (index = 0; index < childMeshes.length; index++) {
  13895. var child = childMeshes[index];
  13896. child.parent = null;
  13897. child.computeWorldMatrix(true);
  13898. }
  13899. }
  13900. this.onAfterWorldMatrixUpdateObservable.clear();
  13901. _super.prototype.dispose.call(this);
  13902. };
  13903. // Statics
  13904. TransformNode.BILLBOARDMODE_NONE = 0;
  13905. TransformNode.BILLBOARDMODE_X = 1;
  13906. TransformNode.BILLBOARDMODE_Y = 2;
  13907. TransformNode.BILLBOARDMODE_Z = 4;
  13908. TransformNode.BILLBOARDMODE_ALL = 7;
  13909. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13910. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13911. __decorate([
  13912. BABYLON.serializeAsVector3()
  13913. ], TransformNode.prototype, "_rotation", void 0);
  13914. __decorate([
  13915. BABYLON.serializeAsQuaternion()
  13916. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  13917. __decorate([
  13918. BABYLON.serializeAsVector3()
  13919. ], TransformNode.prototype, "_scaling", void 0);
  13920. __decorate([
  13921. BABYLON.serialize()
  13922. ], TransformNode.prototype, "billboardMode", void 0);
  13923. __decorate([
  13924. BABYLON.serialize()
  13925. ], TransformNode.prototype, "scalingDeterminant", void 0);
  13926. __decorate([
  13927. BABYLON.serialize()
  13928. ], TransformNode.prototype, "infiniteDistance", void 0);
  13929. __decorate([
  13930. BABYLON.serializeAsVector3()
  13931. ], TransformNode.prototype, "position", void 0);
  13932. return TransformNode;
  13933. }(BABYLON.Node));
  13934. BABYLON.TransformNode = TransformNode;
  13935. })(BABYLON || (BABYLON = {}));
  13936. //# sourceMappingURL=babylon.transformNode.js.map
  13937. var BABYLON;
  13938. (function (BABYLON) {
  13939. var AbstractMesh = /** @class */ (function (_super) {
  13940. __extends(AbstractMesh, _super);
  13941. // Constructor
  13942. function AbstractMesh(name, scene) {
  13943. if (scene === void 0) { scene = null; }
  13944. var _this = _super.call(this, name, scene, false) || this;
  13945. _this._facetNb = 0; // facet number
  13946. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13947. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13948. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13949. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13950. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13951. _this._subDiv = {
  13952. max: 1,
  13953. X: 1,
  13954. Y: 1,
  13955. Z: 1
  13956. };
  13957. _this._facetDepthSort = false; // is the facet depth sort to be computed
  13958. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  13959. // Events
  13960. /**
  13961. * An event triggered when this mesh collides with another one
  13962. * @type {BABYLON.Observable}
  13963. */
  13964. _this.onCollideObservable = new BABYLON.Observable();
  13965. /**
  13966. * An event triggered when the collision's position changes
  13967. * @type {BABYLON.Observable}
  13968. */
  13969. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13970. /**
  13971. * An event triggered when material is changed
  13972. * @type {BABYLON.Observable}
  13973. */
  13974. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13975. // Properties
  13976. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13977. /**
  13978. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13979. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13980. * or
  13981. * 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.
  13982. * for more info check WebGl documentations
  13983. */
  13984. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13985. /**
  13986. * 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:
  13987. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13988. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13989. * 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.
  13990. */
  13991. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13992. /**
  13993. * 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.
  13994. * The default value is -1 which means don't break the query and wait till the result.
  13995. */
  13996. _this.occlusionRetryCount = -1;
  13997. _this._occlusionInternalRetryCounter = 0;
  13998. _this._isOccluded = false;
  13999. _this._isOcclusionQueryInProgress = false;
  14000. _this.visibility = 1.0;
  14001. _this.alphaIndex = Number.MAX_VALUE;
  14002. _this.isVisible = true;
  14003. _this.isPickable = true;
  14004. _this.showBoundingBox = false;
  14005. _this.showSubMeshesBoundingBox = false;
  14006. _this.isBlocker = false;
  14007. _this.enablePointerMoveEvents = false;
  14008. _this.renderingGroupId = 0;
  14009. _this._receiveShadows = false;
  14010. _this.renderOutline = false;
  14011. _this.outlineColor = BABYLON.Color3.Red();
  14012. _this.outlineWidth = 0.02;
  14013. _this.renderOverlay = false;
  14014. _this.overlayColor = BABYLON.Color3.Red();
  14015. _this.overlayAlpha = 0.5;
  14016. _this._hasVertexAlpha = false;
  14017. _this._useVertexColors = true;
  14018. _this._computeBonesUsingShaders = true;
  14019. _this._numBoneInfluencers = 4;
  14020. _this._applyFog = true;
  14021. _this.useOctreeForRenderingSelection = true;
  14022. _this.useOctreeForPicking = true;
  14023. _this.useOctreeForCollisions = true;
  14024. _this._layerMask = 0x0FFFFFFF;
  14025. /**
  14026. * True if the mesh must be rendered in any case.
  14027. */
  14028. _this.alwaysSelectAsActiveMesh = false;
  14029. // Collisions
  14030. _this._checkCollisions = false;
  14031. _this._collisionMask = -1;
  14032. _this._collisionGroup = -1;
  14033. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14034. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14035. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14036. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14037. // Edges
  14038. _this.edgesWidth = 1;
  14039. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14040. // Cache
  14041. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14042. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14043. _this._isDisposed = false;
  14044. _this._renderId = 0;
  14045. _this._intersectionsInProgress = new Array();
  14046. _this._unIndexed = false;
  14047. _this._lightSources = new Array();
  14048. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14049. if (collidedMesh === void 0) { collidedMesh = null; }
  14050. //TODO move this to the collision coordinator!
  14051. if (_this.getScene().workerCollisions)
  14052. newPosition.multiplyInPlace(_this._collider.radius);
  14053. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14054. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14055. _this.position.addInPlace(_this._diffPositionForCollisions);
  14056. }
  14057. if (collidedMesh) {
  14058. _this.onCollideObservable.notifyObservers(collidedMesh);
  14059. }
  14060. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14061. };
  14062. _this.getScene().addMesh(_this);
  14063. _this._resyncLightSources();
  14064. return _this;
  14065. }
  14066. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14067. get: function () {
  14068. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14074. get: function () {
  14075. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14076. },
  14077. enumerable: true,
  14078. configurable: true
  14079. });
  14080. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14081. get: function () {
  14082. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14088. get: function () {
  14089. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14090. },
  14091. enumerable: true,
  14092. configurable: true
  14093. });
  14094. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14095. get: function () {
  14096. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14097. },
  14098. enumerable: true,
  14099. configurable: true
  14100. });
  14101. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14102. /**
  14103. * Read-only : the number of facets in the mesh
  14104. */
  14105. get: function () {
  14106. return this._facetNb;
  14107. },
  14108. enumerable: true,
  14109. configurable: true
  14110. });
  14111. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14112. /**
  14113. * The number (integer) of subdivisions per axis in the partioning space
  14114. */
  14115. get: function () {
  14116. return this._partitioningSubdivisions;
  14117. },
  14118. set: function (nb) {
  14119. this._partitioningSubdivisions = nb;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14125. /**
  14126. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14127. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14128. */
  14129. get: function () {
  14130. return this._partitioningBBoxRatio;
  14131. },
  14132. set: function (ratio) {
  14133. this._partitioningBBoxRatio = ratio;
  14134. },
  14135. enumerable: true,
  14136. configurable: true
  14137. });
  14138. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14139. /**
  14140. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14141. * Works only for updatable meshes.
  14142. * Doesn't work with multi-materials.
  14143. */
  14144. get: function () {
  14145. return this._facetDepthSort;
  14146. },
  14147. set: function (sort) {
  14148. this._facetDepthSort = sort;
  14149. },
  14150. enumerable: true,
  14151. configurable: true
  14152. });
  14153. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14154. /**
  14155. * The location (Vector3) where the facet depth sort must be computed from.
  14156. * By default, the active camera position.
  14157. * Used only when facet depth sort is enabled.
  14158. */
  14159. get: function () {
  14160. return this._facetDepthSortFrom;
  14161. },
  14162. set: function (location) {
  14163. this._facetDepthSortFrom = location;
  14164. },
  14165. enumerable: true,
  14166. configurable: true
  14167. });
  14168. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14169. /**
  14170. * Read-only boolean : is the feature facetData enabled ?
  14171. */
  14172. get: function () {
  14173. return this._facetDataEnabled;
  14174. },
  14175. enumerable: true,
  14176. configurable: true
  14177. });
  14178. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14179. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14180. return false;
  14181. }
  14182. this._markSubMeshesAsMiscDirty();
  14183. return true;
  14184. };
  14185. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14186. set: function (callback) {
  14187. if (this._onCollideObserver) {
  14188. this.onCollideObservable.remove(this._onCollideObserver);
  14189. }
  14190. this._onCollideObserver = this.onCollideObservable.add(callback);
  14191. },
  14192. enumerable: true,
  14193. configurable: true
  14194. });
  14195. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14196. set: function (callback) {
  14197. if (this._onCollisionPositionChangeObserver) {
  14198. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14199. }
  14200. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14201. },
  14202. enumerable: true,
  14203. configurable: true
  14204. });
  14205. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14206. /**
  14207. * 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.
  14208. */
  14209. get: function () {
  14210. return this._isOccluded;
  14211. },
  14212. set: function (value) {
  14213. this._isOccluded = value;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14219. /**
  14220. * Flag to check the progress status of the query
  14221. */
  14222. get: function () {
  14223. return this._isOcclusionQueryInProgress;
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Object.defineProperty(AbstractMesh.prototype, "material", {
  14229. get: function () {
  14230. return this._material;
  14231. },
  14232. set: function (value) {
  14233. if (this._material === value) {
  14234. return;
  14235. }
  14236. this._material = value;
  14237. if (this.onMaterialChangedObservable.hasObservers) {
  14238. this.onMaterialChangedObservable.notifyObservers(this);
  14239. }
  14240. if (!this.subMeshes) {
  14241. return;
  14242. }
  14243. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14244. var subMesh = _a[_i];
  14245. subMesh.setEffect(null);
  14246. }
  14247. },
  14248. enumerable: true,
  14249. configurable: true
  14250. });
  14251. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14252. get: function () {
  14253. return this._receiveShadows;
  14254. },
  14255. set: function (value) {
  14256. if (this._receiveShadows === value) {
  14257. return;
  14258. }
  14259. this._receiveShadows = value;
  14260. this._markSubMeshesAsLightDirty();
  14261. },
  14262. enumerable: true,
  14263. configurable: true
  14264. });
  14265. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14266. get: function () {
  14267. return this._hasVertexAlpha;
  14268. },
  14269. set: function (value) {
  14270. if (this._hasVertexAlpha === value) {
  14271. return;
  14272. }
  14273. this._hasVertexAlpha = value;
  14274. this._markSubMeshesAsAttributesDirty();
  14275. },
  14276. enumerable: true,
  14277. configurable: true
  14278. });
  14279. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14280. get: function () {
  14281. return this._useVertexColors;
  14282. },
  14283. set: function (value) {
  14284. if (this._useVertexColors === value) {
  14285. return;
  14286. }
  14287. this._useVertexColors = value;
  14288. this._markSubMeshesAsAttributesDirty();
  14289. },
  14290. enumerable: true,
  14291. configurable: true
  14292. });
  14293. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14294. get: function () {
  14295. return this._computeBonesUsingShaders;
  14296. },
  14297. set: function (value) {
  14298. if (this._computeBonesUsingShaders === value) {
  14299. return;
  14300. }
  14301. this._computeBonesUsingShaders = value;
  14302. this._markSubMeshesAsAttributesDirty();
  14303. },
  14304. enumerable: true,
  14305. configurable: true
  14306. });
  14307. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14308. get: function () {
  14309. return this._numBoneInfluencers;
  14310. },
  14311. set: function (value) {
  14312. if (this._numBoneInfluencers === value) {
  14313. return;
  14314. }
  14315. this._numBoneInfluencers = value;
  14316. this._markSubMeshesAsAttributesDirty();
  14317. },
  14318. enumerable: true,
  14319. configurable: true
  14320. });
  14321. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14322. get: function () {
  14323. return this._applyFog;
  14324. },
  14325. set: function (value) {
  14326. if (this._applyFog === value) {
  14327. return;
  14328. }
  14329. this._applyFog = value;
  14330. this._markSubMeshesAsMiscDirty();
  14331. },
  14332. enumerable: true,
  14333. configurable: true
  14334. });
  14335. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14336. get: function () {
  14337. return this._layerMask;
  14338. },
  14339. set: function (value) {
  14340. if (value === this._layerMask) {
  14341. return;
  14342. }
  14343. this._layerMask = value;
  14344. this._resyncLightSources();
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14350. get: function () {
  14351. return this._collisionMask;
  14352. },
  14353. set: function (mask) {
  14354. this._collisionMask = !isNaN(mask) ? mask : -1;
  14355. },
  14356. enumerable: true,
  14357. configurable: true
  14358. });
  14359. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14360. get: function () {
  14361. return this._collisionGroup;
  14362. },
  14363. set: function (mask) {
  14364. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14370. get: function () {
  14371. return null;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14377. get: function () {
  14378. return this._skeleton;
  14379. },
  14380. set: function (value) {
  14381. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14382. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14383. }
  14384. if (value && value.needInitialSkinMatrix) {
  14385. value._registerMeshWithPoseMatrix(this);
  14386. }
  14387. this._skeleton = value;
  14388. if (!this._skeleton) {
  14389. this._bonesTransformMatrices = null;
  14390. }
  14391. this._markSubMeshesAsAttributesDirty();
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. /**
  14397. * Boolean : true if the mesh has been disposed.
  14398. */
  14399. AbstractMesh.prototype.isDisposed = function () {
  14400. return this._isDisposed;
  14401. };
  14402. /**
  14403. * Returns the string "AbstractMesh"
  14404. */
  14405. AbstractMesh.prototype.getClassName = function () {
  14406. return "AbstractMesh";
  14407. };
  14408. /**
  14409. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14410. */
  14411. AbstractMesh.prototype.toString = function (fullDetails) {
  14412. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14413. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14414. if (this._skeleton) {
  14415. ret += ", skeleton: " + this._skeleton.name;
  14416. }
  14417. if (fullDetails) {
  14418. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14419. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14420. }
  14421. return ret;
  14422. };
  14423. AbstractMesh.prototype._rebuild = function () {
  14424. if (this._occlusionQuery) {
  14425. this._occlusionQuery = null;
  14426. }
  14427. if (this._edgesRenderer) {
  14428. this._edgesRenderer._rebuild();
  14429. }
  14430. if (!this.subMeshes) {
  14431. return;
  14432. }
  14433. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14434. var subMesh = _a[_i];
  14435. subMesh._rebuild();
  14436. }
  14437. };
  14438. AbstractMesh.prototype._resyncLightSources = function () {
  14439. this._lightSources.length = 0;
  14440. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14441. var light = _a[_i];
  14442. if (!light.isEnabled()) {
  14443. continue;
  14444. }
  14445. if (light.canAffectMesh(this)) {
  14446. this._lightSources.push(light);
  14447. }
  14448. }
  14449. this._markSubMeshesAsLightDirty();
  14450. };
  14451. AbstractMesh.prototype._resyncLighSource = function (light) {
  14452. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14453. var index = this._lightSources.indexOf(light);
  14454. if (index === -1) {
  14455. if (!isIn) {
  14456. return;
  14457. }
  14458. this._lightSources.push(light);
  14459. }
  14460. else {
  14461. if (isIn) {
  14462. return;
  14463. }
  14464. this._lightSources.splice(index, 1);
  14465. }
  14466. this._markSubMeshesAsLightDirty();
  14467. };
  14468. AbstractMesh.prototype._removeLightSource = function (light) {
  14469. var index = this._lightSources.indexOf(light);
  14470. if (index === -1) {
  14471. return;
  14472. }
  14473. this._lightSources.splice(index, 1);
  14474. };
  14475. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14476. if (!this.subMeshes) {
  14477. return;
  14478. }
  14479. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14480. var subMesh = _a[_i];
  14481. if (subMesh._materialDefines) {
  14482. func(subMesh._materialDefines);
  14483. }
  14484. }
  14485. };
  14486. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14487. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14488. };
  14489. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14490. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14491. };
  14492. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14493. if (!this.subMeshes) {
  14494. return;
  14495. }
  14496. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14497. var subMesh = _a[_i];
  14498. var material = subMesh.getMaterial();
  14499. if (material) {
  14500. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14501. }
  14502. }
  14503. };
  14504. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14505. /**
  14506. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14507. * Default : (1.0, 1.0, 1.0)
  14508. */
  14509. get: function () {
  14510. return this._scaling;
  14511. },
  14512. /**
  14513. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14514. * Default : (1.0, 1.0, 1.0)
  14515. */
  14516. set: function (newScaling) {
  14517. this._scaling = newScaling;
  14518. if (this.physicsImpostor) {
  14519. this.physicsImpostor.forceUpdate();
  14520. }
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. // Methods
  14526. /**
  14527. * Disables the mesh edger rendering mode.
  14528. * Returns the AbstractMesh.
  14529. */
  14530. AbstractMesh.prototype.disableEdgesRendering = function () {
  14531. if (this._edgesRenderer) {
  14532. this._edgesRenderer.dispose();
  14533. this._edgesRenderer = null;
  14534. }
  14535. return this;
  14536. };
  14537. /**
  14538. * Enables the edge rendering mode on the mesh.
  14539. * This mode makes the mesh edges visible.
  14540. * Returns the AbstractMesh.
  14541. */
  14542. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14543. if (epsilon === void 0) { epsilon = 0.95; }
  14544. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14545. this.disableEdgesRendering();
  14546. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14547. return this;
  14548. };
  14549. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14550. /**
  14551. * Returns true if the mesh is blocked. Used by the class Mesh.
  14552. * Returns the boolean `false` by default.
  14553. */
  14554. get: function () {
  14555. return false;
  14556. },
  14557. enumerable: true,
  14558. configurable: true
  14559. });
  14560. /**
  14561. * Returns the mesh itself by default, used by the class Mesh.
  14562. * Returned type : AbstractMesh
  14563. */
  14564. AbstractMesh.prototype.getLOD = function (camera) {
  14565. return this;
  14566. };
  14567. /**
  14568. * Returns 0 by default, used by the class Mesh.
  14569. * Returns an integer.
  14570. */
  14571. AbstractMesh.prototype.getTotalVertices = function () {
  14572. return 0;
  14573. };
  14574. /**
  14575. * Returns null by default, used by the class Mesh.
  14576. * Returned type : integer array
  14577. */
  14578. AbstractMesh.prototype.getIndices = function () {
  14579. return null;
  14580. };
  14581. /**
  14582. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14583. * Returned type : float array or Float32Array
  14584. */
  14585. AbstractMesh.prototype.getVerticesData = function (kind) {
  14586. return null;
  14587. };
  14588. /**
  14589. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14590. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14591. * The `data` are either a numeric array either a Float32Array.
  14592. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14593. * 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).
  14594. * Note that a new underlying VertexBuffer object is created each call.
  14595. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14596. *
  14597. * Possible `kind` values :
  14598. * - BABYLON.VertexBuffer.PositionKind
  14599. * - BABYLON.VertexBuffer.UVKind
  14600. * - BABYLON.VertexBuffer.UV2Kind
  14601. * - BABYLON.VertexBuffer.UV3Kind
  14602. * - BABYLON.VertexBuffer.UV4Kind
  14603. * - BABYLON.VertexBuffer.UV5Kind
  14604. * - BABYLON.VertexBuffer.UV6Kind
  14605. * - BABYLON.VertexBuffer.ColorKind
  14606. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14607. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14608. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14609. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14610. *
  14611. * Returns the Mesh.
  14612. */
  14613. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14614. return this;
  14615. };
  14616. /**
  14617. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14618. * If the mesh has no geometry, it is simply returned as it is.
  14619. * The `data` are either a numeric array either a Float32Array.
  14620. * No new underlying VertexBuffer object is created.
  14621. * 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.
  14622. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14623. *
  14624. * Possible `kind` values :
  14625. * - BABYLON.VertexBuffer.PositionKind
  14626. * - BABYLON.VertexBuffer.UVKind
  14627. * - BABYLON.VertexBuffer.UV2Kind
  14628. * - BABYLON.VertexBuffer.UV3Kind
  14629. * - BABYLON.VertexBuffer.UV4Kind
  14630. * - BABYLON.VertexBuffer.UV5Kind
  14631. * - BABYLON.VertexBuffer.UV6Kind
  14632. * - BABYLON.VertexBuffer.ColorKind
  14633. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14634. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14635. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14636. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14637. *
  14638. * Returns the Mesh.
  14639. */
  14640. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14641. return this;
  14642. };
  14643. /**
  14644. * Sets the mesh indices.
  14645. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14646. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14647. * This method creates a new index buffer each call.
  14648. * Returns the Mesh.
  14649. */
  14650. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14651. return this;
  14652. };
  14653. /** Returns false by default, used by the class Mesh.
  14654. * Returns a boolean
  14655. */
  14656. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14657. return false;
  14658. };
  14659. /**
  14660. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14661. * Returns a BoundingInfo
  14662. */
  14663. AbstractMesh.prototype.getBoundingInfo = function () {
  14664. if (this._masterMesh) {
  14665. return this._masterMesh.getBoundingInfo();
  14666. }
  14667. if (!this._boundingInfo) {
  14668. // this._boundingInfo is being created here
  14669. this._updateBoundingInfo();
  14670. }
  14671. // cannot be null.
  14672. return this._boundingInfo;
  14673. };
  14674. /**
  14675. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14676. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14677. */
  14678. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14679. if (includeDescendants === void 0) { includeDescendants = true; }
  14680. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14681. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14682. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14683. if (maxDimension === 0) {
  14684. return this;
  14685. }
  14686. var scale = 1 / maxDimension;
  14687. this.scaling.scaleInPlace(scale);
  14688. return this;
  14689. };
  14690. /**
  14691. * Sets a mesh new object BoundingInfo.
  14692. * Returns the AbstractMesh.
  14693. */
  14694. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14695. this._boundingInfo = boundingInfo;
  14696. return this;
  14697. };
  14698. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14699. get: function () {
  14700. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14701. },
  14702. enumerable: true,
  14703. configurable: true
  14704. });
  14705. AbstractMesh.prototype._preActivate = function () {
  14706. };
  14707. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14708. };
  14709. AbstractMesh.prototype._activate = function (renderId) {
  14710. this._renderId = renderId;
  14711. };
  14712. /**
  14713. * Returns the latest update of the World matrix
  14714. * Returns a Matrix.
  14715. */
  14716. AbstractMesh.prototype.getWorldMatrix = function () {
  14717. if (this._masterMesh) {
  14718. return this._masterMesh.getWorldMatrix();
  14719. }
  14720. return _super.prototype.getWorldMatrix.call(this);
  14721. };
  14722. // ================================== Point of View Movement =================================
  14723. /**
  14724. * Perform relative position change from the point of view of behind the front of the mesh.
  14725. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14726. * Supports definition of mesh facing forward or backward.
  14727. * @param {number} amountRight
  14728. * @param {number} amountUp
  14729. * @param {number} amountForward
  14730. *
  14731. * Returns the AbstractMesh.
  14732. */
  14733. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14734. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14735. return this;
  14736. };
  14737. /**
  14738. * Calculate relative position change from the point of view of behind the front of the mesh.
  14739. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14740. * Supports definition of mesh facing forward or backward.
  14741. * @param {number} amountRight
  14742. * @param {number} amountUp
  14743. * @param {number} amountForward
  14744. *
  14745. * Returns a new Vector3.
  14746. */
  14747. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14748. var rotMatrix = new BABYLON.Matrix();
  14749. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14750. rotQuaternion.toRotationMatrix(rotMatrix);
  14751. var translationDelta = BABYLON.Vector3.Zero();
  14752. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14754. return translationDelta;
  14755. };
  14756. // ================================== Point of View Rotation =================================
  14757. /**
  14758. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14759. * Supports definition of mesh facing forward or backward.
  14760. * @param {number} flipBack
  14761. * @param {number} twirlClockwise
  14762. * @param {number} tiltRight
  14763. *
  14764. * Returns the AbstractMesh.
  14765. */
  14766. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14767. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14768. return this;
  14769. };
  14770. /**
  14771. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14772. * Supports definition of mesh facing forward or backward.
  14773. * @param {number} flipBack
  14774. * @param {number} twirlClockwise
  14775. * @param {number} tiltRight
  14776. *
  14777. * Returns a new Vector3.
  14778. */
  14779. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14780. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14781. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14782. };
  14783. /**
  14784. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14785. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14786. */
  14787. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14788. if (includeDescendants === void 0) { includeDescendants = true; }
  14789. this.computeWorldMatrix(true);
  14790. var min;
  14791. var max;
  14792. var boundingInfo = this.getBoundingInfo();
  14793. if (!this.subMeshes) {
  14794. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14795. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14796. }
  14797. else {
  14798. min = boundingInfo.boundingBox.minimumWorld;
  14799. max = boundingInfo.boundingBox.maximumWorld;
  14800. }
  14801. if (includeDescendants) {
  14802. var descendants = this.getDescendants(false);
  14803. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14804. var descendant = descendants_1[_i];
  14805. var childMesh = descendant;
  14806. childMesh.computeWorldMatrix(true);
  14807. var childBoundingInfo = childMesh.getBoundingInfo();
  14808. if (childMesh.getTotalVertices() === 0) {
  14809. continue;
  14810. }
  14811. var boundingBox = childBoundingInfo.boundingBox;
  14812. var minBox = boundingBox.minimumWorld;
  14813. var maxBox = boundingBox.maximumWorld;
  14814. BABYLON.Tools.CheckExtends(minBox, min, max);
  14815. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14816. }
  14817. }
  14818. return {
  14819. min: min,
  14820. max: max
  14821. };
  14822. };
  14823. /**
  14824. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14825. * Returns the AbstractMesh.
  14826. */
  14827. AbstractMesh.prototype._updateBoundingInfo = function () {
  14828. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14829. this._boundingInfo.update(this.worldMatrixFromCache);
  14830. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14831. return this;
  14832. };
  14833. /**
  14834. * Update a mesh's children BoundingInfo objects only.
  14835. * Returns the AbstractMesh.
  14836. */
  14837. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14838. if (!this.subMeshes) {
  14839. return this;
  14840. }
  14841. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14842. var subMesh = this.subMeshes[subIndex];
  14843. if (!subMesh.IsGlobal) {
  14844. subMesh.updateBoundingInfo(matrix);
  14845. }
  14846. }
  14847. return this;
  14848. };
  14849. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14850. // Bounding info
  14851. this._updateBoundingInfo();
  14852. };
  14853. /**
  14854. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14855. * A mesh is in the frustum if its bounding box intersects the frustum.
  14856. * Boolean returned.
  14857. */
  14858. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14859. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14860. };
  14861. /**
  14862. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14863. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14864. * Boolean returned.
  14865. */
  14866. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14867. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14868. ;
  14869. };
  14870. /**
  14871. * True if the mesh intersects another mesh or a SolidParticle object.
  14872. * 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)
  14873. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14874. * Returns a boolean.
  14875. */
  14876. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14877. if (precise === void 0) { precise = false; }
  14878. if (!this._boundingInfo || !mesh._boundingInfo) {
  14879. return false;
  14880. }
  14881. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14882. return true;
  14883. }
  14884. if (includeDescendants) {
  14885. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14886. var child = _a[_i];
  14887. if (child.intersectsMesh(mesh, precise, true)) {
  14888. return true;
  14889. }
  14890. }
  14891. }
  14892. return false;
  14893. };
  14894. /**
  14895. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14896. * Returns a boolean.
  14897. */
  14898. AbstractMesh.prototype.intersectsPoint = function (point) {
  14899. if (!this._boundingInfo) {
  14900. return false;
  14901. }
  14902. return this._boundingInfo.intersectsPoint(point);
  14903. };
  14904. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14905. return this.physicsImpostor;
  14906. };
  14907. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14908. if (camera === void 0) { camera = null; }
  14909. if (!camera) {
  14910. camera = this.getScene().activeCamera;
  14911. }
  14912. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14913. };
  14914. /**
  14915. * Returns the distance from the mesh to the active camera.
  14916. * Returns a float.
  14917. */
  14918. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14919. if (camera === void 0) { camera = null; }
  14920. if (!camera) {
  14921. camera = this.getScene().activeCamera;
  14922. }
  14923. return this.absolutePosition.subtract(camera.position).length();
  14924. };
  14925. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14926. if (!this.physicsImpostor) {
  14927. return this;
  14928. }
  14929. this.physicsImpostor.applyImpulse(force, contactPoint);
  14930. return this;
  14931. };
  14932. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14933. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14934. return this;
  14935. }
  14936. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14937. mainPivot: pivot1,
  14938. connectedPivot: pivot2,
  14939. nativeParams: options
  14940. });
  14941. return this;
  14942. };
  14943. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14944. // Collisions
  14945. /**
  14946. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14947. * Default `false`.
  14948. */
  14949. get: function () {
  14950. return this._checkCollisions;
  14951. },
  14952. set: function (collisionEnabled) {
  14953. this._checkCollisions = collisionEnabled;
  14954. if (this.getScene().workerCollisions) {
  14955. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14956. }
  14957. },
  14958. enumerable: true,
  14959. configurable: true
  14960. });
  14961. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14962. var globalPosition = this.getAbsolutePosition();
  14963. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14964. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14965. if (!this._collider) {
  14966. this._collider = new BABYLON.Collider();
  14967. }
  14968. this._collider.radius = this.ellipsoid;
  14969. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14970. return this;
  14971. };
  14972. // Submeshes octree
  14973. /**
  14974. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14975. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14976. * Returns an Octree of submeshes.
  14977. */
  14978. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14979. if (maxCapacity === void 0) { maxCapacity = 64; }
  14980. if (maxDepth === void 0) { maxDepth = 2; }
  14981. if (!this._submeshesOctree) {
  14982. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14983. }
  14984. this.computeWorldMatrix(true);
  14985. var boundingInfo = this.getBoundingInfo();
  14986. // Update octree
  14987. var bbox = boundingInfo.boundingBox;
  14988. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14989. return this._submeshesOctree;
  14990. };
  14991. // Collisions
  14992. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14993. this._generatePointsArray();
  14994. if (!this._positions) {
  14995. return this;
  14996. }
  14997. // Transformation
  14998. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14999. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15000. subMesh._lastColliderWorldVertices = [];
  15001. subMesh._trianglePlanes = [];
  15002. var start = subMesh.verticesStart;
  15003. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15004. for (var i = start; i < end; i++) {
  15005. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15006. }
  15007. }
  15008. // Collide
  15009. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15010. if (collider.collisionFound) {
  15011. collider.collidedMesh = this;
  15012. }
  15013. return this;
  15014. };
  15015. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15016. var subMeshes;
  15017. var len;
  15018. // Octrees
  15019. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15020. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  15021. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  15022. len = intersections.length;
  15023. subMeshes = intersections.data;
  15024. }
  15025. else {
  15026. subMeshes = this.subMeshes;
  15027. len = subMeshes.length;
  15028. }
  15029. for (var index = 0; index < len; index++) {
  15030. var subMesh = subMeshes[index];
  15031. // Bounding test
  15032. if (len > 1 && !subMesh._checkCollision(collider))
  15033. continue;
  15034. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15035. }
  15036. return this;
  15037. };
  15038. AbstractMesh.prototype._checkCollision = function (collider) {
  15039. // Bounding box test
  15040. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15041. return this;
  15042. // Transformation matrix
  15043. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  15044. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15045. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15046. return this;
  15047. };
  15048. // Picking
  15049. AbstractMesh.prototype._generatePointsArray = function () {
  15050. return false;
  15051. };
  15052. /**
  15053. * Checks if the passed Ray intersects with the mesh.
  15054. * Returns an object PickingInfo.
  15055. */
  15056. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15057. var pickingInfo = new BABYLON.PickingInfo();
  15058. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15059. return pickingInfo;
  15060. }
  15061. if (!this._generatePointsArray()) {
  15062. return pickingInfo;
  15063. }
  15064. var intersectInfo = null;
  15065. // Octrees
  15066. var subMeshes;
  15067. var len;
  15068. if (this._submeshesOctree && this.useOctreeForPicking) {
  15069. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15070. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15071. len = intersections.length;
  15072. subMeshes = intersections.data;
  15073. }
  15074. else {
  15075. subMeshes = this.subMeshes;
  15076. len = subMeshes.length;
  15077. }
  15078. for (var index = 0; index < len; index++) {
  15079. var subMesh = subMeshes[index];
  15080. // Bounding test
  15081. if (len > 1 && !subMesh.canIntersects(ray))
  15082. continue;
  15083. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15084. if (currentIntersectInfo) {
  15085. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15086. intersectInfo = currentIntersectInfo;
  15087. intersectInfo.subMeshId = index;
  15088. if (fastCheck) {
  15089. break;
  15090. }
  15091. }
  15092. }
  15093. }
  15094. if (intersectInfo) {
  15095. // Get picked point
  15096. var world = this.getWorldMatrix();
  15097. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15098. var direction = ray.direction.clone();
  15099. direction = direction.scale(intersectInfo.distance);
  15100. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15101. var pickedPoint = worldOrigin.add(worldDirection);
  15102. // Return result
  15103. pickingInfo.hit = true;
  15104. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15105. pickingInfo.pickedPoint = pickedPoint;
  15106. pickingInfo.pickedMesh = this;
  15107. pickingInfo.bu = intersectInfo.bu || 0;
  15108. pickingInfo.bv = intersectInfo.bv || 0;
  15109. pickingInfo.faceId = intersectInfo.faceId;
  15110. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15111. return pickingInfo;
  15112. }
  15113. return pickingInfo;
  15114. };
  15115. /**
  15116. * Clones the mesh, used by the class Mesh.
  15117. * Just returns `null` for an AbstractMesh.
  15118. */
  15119. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15120. return null;
  15121. };
  15122. /**
  15123. * Disposes all the mesh submeshes.
  15124. * Returns the AbstractMesh.
  15125. */
  15126. AbstractMesh.prototype.releaseSubMeshes = function () {
  15127. if (this.subMeshes) {
  15128. while (this.subMeshes.length) {
  15129. this.subMeshes[0].dispose();
  15130. }
  15131. }
  15132. else {
  15133. this.subMeshes = new Array();
  15134. }
  15135. return this;
  15136. };
  15137. /**
  15138. * Disposes the AbstractMesh.
  15139. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15140. * Returns nothing.
  15141. */
  15142. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15143. var _this = this;
  15144. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15145. var index;
  15146. // Action manager
  15147. if (this.actionManager) {
  15148. this.actionManager.dispose();
  15149. this.actionManager = null;
  15150. }
  15151. // Skeleton
  15152. this.skeleton = null;
  15153. // Physics
  15154. if (this.physicsImpostor) {
  15155. this.physicsImpostor.dispose();
  15156. }
  15157. // Intersections in progress
  15158. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15159. var other = this._intersectionsInProgress[index];
  15160. var pos = other._intersectionsInProgress.indexOf(this);
  15161. other._intersectionsInProgress.splice(pos, 1);
  15162. }
  15163. this._intersectionsInProgress = [];
  15164. // Lights
  15165. var lights = this.getScene().lights;
  15166. lights.forEach(function (light) {
  15167. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15168. if (meshIndex !== -1) {
  15169. light.includedOnlyMeshes.splice(meshIndex, 1);
  15170. }
  15171. meshIndex = light.excludedMeshes.indexOf(_this);
  15172. if (meshIndex !== -1) {
  15173. light.excludedMeshes.splice(meshIndex, 1);
  15174. }
  15175. // Shadow generators
  15176. var generator = light.getShadowGenerator();
  15177. if (generator) {
  15178. var shadowMap = generator.getShadowMap();
  15179. if (shadowMap && shadowMap.renderList) {
  15180. meshIndex = shadowMap.renderList.indexOf(_this);
  15181. if (meshIndex !== -1) {
  15182. shadowMap.renderList.splice(meshIndex, 1);
  15183. }
  15184. }
  15185. }
  15186. });
  15187. // Edges
  15188. if (this._edgesRenderer) {
  15189. this._edgesRenderer.dispose();
  15190. this._edgesRenderer = null;
  15191. }
  15192. // SubMeshes
  15193. if (this.getClassName() !== "InstancedMesh") {
  15194. this.releaseSubMeshes();
  15195. }
  15196. // Octree
  15197. var sceneOctree = this.getScene().selectionOctree;
  15198. if (sceneOctree) {
  15199. var index = sceneOctree.dynamicContent.indexOf(this);
  15200. if (index !== -1) {
  15201. sceneOctree.dynamicContent.splice(index, 1);
  15202. }
  15203. }
  15204. // Query
  15205. var engine = this.getScene().getEngine();
  15206. if (this._occlusionQuery) {
  15207. this._isOcclusionQueryInProgress = false;
  15208. engine.deleteQuery(this._occlusionQuery);
  15209. this._occlusionQuery = null;
  15210. }
  15211. // Engine
  15212. engine.wipeCaches();
  15213. // Remove from scene
  15214. this.getScene().removeMesh(this);
  15215. if (disposeMaterialAndTextures) {
  15216. if (this.material) {
  15217. this.material.dispose(false, true);
  15218. }
  15219. }
  15220. if (!doNotRecurse) {
  15221. // Particles
  15222. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15223. if (this.getScene().particleSystems[index].emitter === this) {
  15224. this.getScene().particleSystems[index].dispose();
  15225. index--;
  15226. }
  15227. }
  15228. }
  15229. // facet data
  15230. if (this._facetDataEnabled) {
  15231. this.disableFacetData();
  15232. }
  15233. this.onAfterWorldMatrixUpdateObservable.clear();
  15234. this.onCollideObservable.clear();
  15235. this.onCollisionPositionChangeObservable.clear();
  15236. this._isDisposed = true;
  15237. _super.prototype.dispose.call(this, doNotRecurse);
  15238. };
  15239. /**
  15240. * Adds the passed mesh as a child to the current mesh.
  15241. * Returns the AbstractMesh.
  15242. */
  15243. AbstractMesh.prototype.addChild = function (mesh) {
  15244. mesh.setParent(this);
  15245. return this;
  15246. };
  15247. /**
  15248. * Removes the passed mesh from the current mesh children list.
  15249. * Returns the AbstractMesh.
  15250. */
  15251. AbstractMesh.prototype.removeChild = function (mesh) {
  15252. mesh.setParent(null);
  15253. return this;
  15254. };
  15255. // Facet data
  15256. /**
  15257. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15258. * Returns the AbstractMesh.
  15259. */
  15260. AbstractMesh.prototype._initFacetData = function () {
  15261. if (!this._facetNormals) {
  15262. this._facetNormals = new Array();
  15263. }
  15264. if (!this._facetPositions) {
  15265. this._facetPositions = new Array();
  15266. }
  15267. if (!this._facetPartitioning) {
  15268. this._facetPartitioning = new Array();
  15269. }
  15270. this._facetNb = (this.getIndices().length / 3) | 0;
  15271. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15272. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15273. for (var f = 0; f < this._facetNb; f++) {
  15274. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15275. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15276. }
  15277. this._facetDataEnabled = true;
  15278. return this;
  15279. };
  15280. /**
  15281. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15282. * This method can be called within the render loop.
  15283. * 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.
  15284. * Returns the AbstractMesh.
  15285. */
  15286. AbstractMesh.prototype.updateFacetData = function () {
  15287. if (!this._facetDataEnabled) {
  15288. this._initFacetData();
  15289. }
  15290. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15291. var indices = this.getIndices();
  15292. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15293. var bInfo = this.getBoundingInfo();
  15294. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15295. // init arrays, matrix and sort function on first call
  15296. this._facetDepthSortEnabled = true;
  15297. if (indices instanceof Uint16Array) {
  15298. this._depthSortedIndices = new Uint16Array(indices);
  15299. }
  15300. else if (indices instanceof Uint32Array) {
  15301. this._depthSortedIndices = new Uint32Array(indices);
  15302. }
  15303. else {
  15304. var needs32bits = false;
  15305. for (var i = 0; i < indices.length; i++) {
  15306. if (indices[i] > 65535) {
  15307. needs32bits = true;
  15308. break;
  15309. }
  15310. }
  15311. if (needs32bits) {
  15312. this._depthSortedIndices = new Uint32Array(indices);
  15313. }
  15314. else {
  15315. this._depthSortedIndices = new Uint16Array(indices);
  15316. }
  15317. }
  15318. this._facetDepthSortFunction = function (f1, f2) {
  15319. return (f2.sqDistance - f1.sqDistance);
  15320. };
  15321. if (!this._facetDepthSortFrom) {
  15322. var camera = this.getScene().activeCamera;
  15323. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15324. }
  15325. this._depthSortedFacets = [];
  15326. for (var f = 0; f < this._facetNb; f++) {
  15327. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15328. this._depthSortedFacets.push(depthSortedFacet);
  15329. }
  15330. this._invertedMatrix = BABYLON.Matrix.Identity();
  15331. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15332. }
  15333. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15334. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15335. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15336. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15337. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15338. this._subDiv.max = this._partitioningSubdivisions;
  15339. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15340. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15341. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15342. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15343. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15344. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15345. // set the parameters for ComputeNormals()
  15346. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15347. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15348. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15349. this._facetParameters.bInfo = bInfo;
  15350. this._facetParameters.bbSize = this._bbSize;
  15351. this._facetParameters.subDiv = this._subDiv;
  15352. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15353. this._facetParameters.depthSort = this._facetDepthSort;
  15354. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15355. this.computeWorldMatrix(true);
  15356. this._worldMatrix.invertToRef(this._invertedMatrix);
  15357. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15358. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15359. }
  15360. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15361. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15362. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15363. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15364. var l = (this._depthSortedIndices.length / 3) | 0;
  15365. for (var f = 0; f < l; f++) {
  15366. var sind = this._depthSortedFacets[f].ind;
  15367. this._depthSortedIndices[f * 3] = indices[sind];
  15368. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15369. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15370. }
  15371. this.updateIndices(this._depthSortedIndices);
  15372. }
  15373. return this;
  15374. };
  15375. /**
  15376. * Returns the facetLocalNormals array.
  15377. * The normals are expressed in the mesh local space.
  15378. */
  15379. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15380. if (!this._facetNormals) {
  15381. this.updateFacetData();
  15382. }
  15383. return this._facetNormals;
  15384. };
  15385. /**
  15386. * Returns the facetLocalPositions array.
  15387. * The facet positions are expressed in the mesh local space.
  15388. */
  15389. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15390. if (!this._facetPositions) {
  15391. this.updateFacetData();
  15392. }
  15393. return this._facetPositions;
  15394. };
  15395. /**
  15396. * Returns the facetLocalPartioning array.
  15397. */
  15398. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15399. if (!this._facetPartitioning) {
  15400. this.updateFacetData();
  15401. }
  15402. return this._facetPartitioning;
  15403. };
  15404. /**
  15405. * Returns the i-th facet position in the world system.
  15406. * This method allocates a new Vector3 per call.
  15407. */
  15408. AbstractMesh.prototype.getFacetPosition = function (i) {
  15409. var pos = BABYLON.Vector3.Zero();
  15410. this.getFacetPositionToRef(i, pos);
  15411. return pos;
  15412. };
  15413. /**
  15414. * Sets the reference Vector3 with the i-th facet position in the world system.
  15415. * Returns the AbstractMesh.
  15416. */
  15417. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15418. var localPos = (this.getFacetLocalPositions())[i];
  15419. var world = this.getWorldMatrix();
  15420. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15421. return this;
  15422. };
  15423. /**
  15424. * Returns the i-th facet normal in the world system.
  15425. * This method allocates a new Vector3 per call.
  15426. */
  15427. AbstractMesh.prototype.getFacetNormal = function (i) {
  15428. var norm = BABYLON.Vector3.Zero();
  15429. this.getFacetNormalToRef(i, norm);
  15430. return norm;
  15431. };
  15432. /**
  15433. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15434. * Returns the AbstractMesh.
  15435. */
  15436. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15437. var localNorm = (this.getFacetLocalNormals())[i];
  15438. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15439. return this;
  15440. };
  15441. /**
  15442. * 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).
  15443. */
  15444. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15445. var bInfo = this.getBoundingInfo();
  15446. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15447. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15448. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15449. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15450. return null;
  15451. }
  15452. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15453. };
  15454. /**
  15455. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15456. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15457. * 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.
  15458. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15459. * 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.
  15460. */
  15461. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15462. if (checkFace === void 0) { checkFace = false; }
  15463. if (facing === void 0) { facing = true; }
  15464. var world = this.getWorldMatrix();
  15465. var invMat = BABYLON.Tmp.Matrix[5];
  15466. world.invertToRef(invMat);
  15467. var invVect = BABYLON.Tmp.Vector3[8];
  15468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15469. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15470. if (projected) {
  15471. // tranform the local computed projected vector to world coordinates
  15472. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15473. }
  15474. return closest;
  15475. };
  15476. /**
  15477. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15478. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15479. * 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.
  15480. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15481. * 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.
  15482. */
  15483. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15484. if (checkFace === void 0) { checkFace = false; }
  15485. if (facing === void 0) { facing = true; }
  15486. var closest = null;
  15487. var tmpx = 0.0;
  15488. var tmpy = 0.0;
  15489. var tmpz = 0.0;
  15490. var d = 0.0; // tmp dot facet normal * facet position
  15491. var t0 = 0.0;
  15492. var projx = 0.0;
  15493. var projy = 0.0;
  15494. var projz = 0.0;
  15495. // Get all the facets in the same partitioning block than (x, y, z)
  15496. var facetPositions = this.getFacetLocalPositions();
  15497. var facetNormals = this.getFacetLocalNormals();
  15498. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15499. if (!facetsInBlock) {
  15500. return null;
  15501. }
  15502. // Get the closest facet to (x, y, z)
  15503. var shortest = Number.MAX_VALUE; // init distance vars
  15504. var tmpDistance = shortest;
  15505. var fib; // current facet in the block
  15506. var norm; // current facet normal
  15507. var p0; // current facet barycenter position
  15508. // loop on all the facets in the current partitioning block
  15509. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15510. fib = facetsInBlock[idx];
  15511. norm = facetNormals[fib];
  15512. p0 = facetPositions[fib];
  15513. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15514. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15515. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15516. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15517. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15518. projx = x + norm.x * t0;
  15519. projy = y + norm.y * t0;
  15520. projz = z + norm.z * t0;
  15521. tmpx = projx - x;
  15522. tmpy = projy - y;
  15523. tmpz = projz - z;
  15524. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15525. if (tmpDistance < shortest) {
  15526. shortest = tmpDistance;
  15527. closest = fib;
  15528. if (projected) {
  15529. projected.x = projx;
  15530. projected.y = projy;
  15531. projected.z = projz;
  15532. }
  15533. }
  15534. }
  15535. }
  15536. return closest;
  15537. };
  15538. /**
  15539. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15540. */
  15541. AbstractMesh.prototype.getFacetDataParameters = function () {
  15542. return this._facetParameters;
  15543. };
  15544. /**
  15545. * Disables the feature FacetData and frees the related memory.
  15546. * Returns the AbstractMesh.
  15547. */
  15548. AbstractMesh.prototype.disableFacetData = function () {
  15549. if (this._facetDataEnabled) {
  15550. this._facetDataEnabled = false;
  15551. this._facetPositions = new Array();
  15552. this._facetNormals = new Array();
  15553. this._facetPartitioning = new Array();
  15554. this._facetParameters = null;
  15555. this._depthSortedIndices = new Uint32Array(0);
  15556. }
  15557. return this;
  15558. };
  15559. /**
  15560. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15561. * Returns the mesh.
  15562. */
  15563. AbstractMesh.prototype.updateIndices = function (indices) {
  15564. return this;
  15565. };
  15566. /**
  15567. * The mesh Geometry. Actually used by the Mesh object.
  15568. * Returns a blank geometry object.
  15569. */
  15570. /**
  15571. * Creates new normals data for the mesh.
  15572. * @param updatable.
  15573. */
  15574. AbstractMesh.prototype.createNormals = function (updatable) {
  15575. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15576. var indices = this.getIndices();
  15577. var normals;
  15578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15579. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15580. }
  15581. else {
  15582. normals = [];
  15583. }
  15584. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15585. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15586. };
  15587. /**
  15588. * Align the mesh with a normal.
  15589. * Returns the mesh.
  15590. */
  15591. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15592. if (!upDirection) {
  15593. upDirection = BABYLON.Axis.Y;
  15594. }
  15595. var axisX = BABYLON.Tmp.Vector3[0];
  15596. var axisZ = BABYLON.Tmp.Vector3[1];
  15597. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15598. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15599. if (this.rotationQuaternion) {
  15600. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15601. }
  15602. else {
  15603. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15604. }
  15605. return this;
  15606. };
  15607. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15608. var engine = this.getEngine();
  15609. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15610. this._isOccluded = false;
  15611. return;
  15612. }
  15613. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15614. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15615. if (isOcclusionQueryAvailable) {
  15616. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15617. this._isOcclusionQueryInProgress = false;
  15618. this._occlusionInternalRetryCounter = 0;
  15619. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15620. }
  15621. else {
  15622. this._occlusionInternalRetryCounter++;
  15623. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15624. this._isOcclusionQueryInProgress = false;
  15625. this._occlusionInternalRetryCounter = 0;
  15626. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15627. // if strict continue the last state of the object.
  15628. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15629. }
  15630. else {
  15631. return;
  15632. }
  15633. }
  15634. }
  15635. var scene = this.getScene();
  15636. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15637. if (!this._occlusionQuery) {
  15638. this._occlusionQuery = engine.createQuery();
  15639. }
  15640. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15641. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15642. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15643. this._isOcclusionQueryInProgress = true;
  15644. };
  15645. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15646. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15647. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15648. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15649. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15650. return AbstractMesh;
  15651. }(BABYLON.TransformNode));
  15652. BABYLON.AbstractMesh = AbstractMesh;
  15653. })(BABYLON || (BABYLON = {}));
  15654. //# sourceMappingURL=babylon.abstractMesh.js.map
  15655. var BABYLON;
  15656. (function (BABYLON) {
  15657. var Light = /** @class */ (function (_super) {
  15658. __extends(Light, _super);
  15659. /**
  15660. * Creates a Light object in the scene.
  15661. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15662. */
  15663. function Light(name, scene) {
  15664. var _this = _super.call(this, name, scene) || this;
  15665. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15666. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15667. _this.intensity = 1.0;
  15668. _this.range = Number.MAX_VALUE;
  15669. /**
  15670. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15671. * of light.
  15672. */
  15673. _this._photometricScale = 1.0;
  15674. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15675. _this._radius = 0.00001;
  15676. _this.renderPriority = 0;
  15677. /**
  15678. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15679. * the current shadow generator.
  15680. */
  15681. _this.shadowEnabled = true;
  15682. _this._excludeWithLayerMask = 0;
  15683. _this._includeOnlyWithLayerMask = 0;
  15684. _this._lightmapMode = 0;
  15685. _this._excludedMeshesIds = new Array();
  15686. _this._includedOnlyMeshesIds = new Array();
  15687. _this.getScene().addLight(_this);
  15688. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15689. _this._buildUniformLayout();
  15690. _this.includedOnlyMeshes = new Array();
  15691. _this.excludedMeshes = new Array();
  15692. _this._resyncMeshes();
  15693. return _this;
  15694. }
  15695. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15696. /**
  15697. * If every light affecting the material is in this lightmapMode,
  15698. * material.lightmapTexture adds or multiplies
  15699. * (depends on material.useLightmapAsShadowmap)
  15700. * after every other light calculations.
  15701. */
  15702. get: function () {
  15703. return Light._LIGHTMAP_DEFAULT;
  15704. },
  15705. enumerable: true,
  15706. configurable: true
  15707. });
  15708. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15709. /**
  15710. * material.lightmapTexture as only diffuse lighting from this light
  15711. * adds pnly specular lighting from this light
  15712. * adds dynamic shadows
  15713. */
  15714. get: function () {
  15715. return Light._LIGHTMAP_SPECULAR;
  15716. },
  15717. enumerable: true,
  15718. configurable: true
  15719. });
  15720. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15721. /**
  15722. * material.lightmapTexture as only lighting
  15723. * no light calculation from this light
  15724. * only adds dynamic shadows from this light
  15725. */
  15726. get: function () {
  15727. return Light._LIGHTMAP_SHADOWSONLY;
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15733. /**
  15734. * Each light type uses the default quantity according to its type:
  15735. * point/spot lights use luminous intensity
  15736. * directional lights use illuminance
  15737. */
  15738. get: function () {
  15739. return Light._INTENSITYMODE_AUTOMATIC;
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15745. /**
  15746. * lumen (lm)
  15747. */
  15748. get: function () {
  15749. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15750. },
  15751. enumerable: true,
  15752. configurable: true
  15753. });
  15754. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15755. /**
  15756. * candela (lm/sr)
  15757. */
  15758. get: function () {
  15759. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15765. /**
  15766. * lux (lm/m^2)
  15767. */
  15768. get: function () {
  15769. return Light._INTENSITYMODE_ILLUMINANCE;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15775. /**
  15776. * nit (cd/m^2)
  15777. */
  15778. get: function () {
  15779. return Light._INTENSITYMODE_LUMINANCE;
  15780. },
  15781. enumerable: true,
  15782. configurable: true
  15783. });
  15784. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15785. /**
  15786. * Light type const id of the point light.
  15787. */
  15788. get: function () {
  15789. return Light._LIGHTTYPEID_POINTLIGHT;
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15795. /**
  15796. * Light type const id of the directional light.
  15797. */
  15798. get: function () {
  15799. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15800. },
  15801. enumerable: true,
  15802. configurable: true
  15803. });
  15804. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15805. /**
  15806. * Light type const id of the spot light.
  15807. */
  15808. get: function () {
  15809. return Light._LIGHTTYPEID_SPOTLIGHT;
  15810. },
  15811. enumerable: true,
  15812. configurable: true
  15813. });
  15814. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15815. /**
  15816. * Light type const id of the hemispheric light.
  15817. */
  15818. get: function () {
  15819. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15820. },
  15821. enumerable: true,
  15822. configurable: true
  15823. });
  15824. Object.defineProperty(Light.prototype, "intensityMode", {
  15825. /**
  15826. * Gets the photometric scale used to interpret the intensity.
  15827. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15828. */
  15829. get: function () {
  15830. return this._intensityMode;
  15831. },
  15832. /**
  15833. * Sets the photometric scale used to interpret the intensity.
  15834. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15835. */
  15836. set: function (value) {
  15837. this._intensityMode = value;
  15838. this._computePhotometricScale();
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. ;
  15844. ;
  15845. Object.defineProperty(Light.prototype, "radius", {
  15846. /**
  15847. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15848. */
  15849. get: function () {
  15850. return this._radius;
  15851. },
  15852. /**
  15853. * sets the light radius used by PBR Materials to simulate soft area lights.
  15854. */
  15855. set: function (value) {
  15856. this._radius = value;
  15857. this._computePhotometricScale();
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. ;
  15863. ;
  15864. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15865. get: function () {
  15866. return this._includedOnlyMeshes;
  15867. },
  15868. set: function (value) {
  15869. this._includedOnlyMeshes = value;
  15870. this._hookArrayForIncludedOnly(value);
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15876. get: function () {
  15877. return this._excludedMeshes;
  15878. },
  15879. set: function (value) {
  15880. this._excludedMeshes = value;
  15881. this._hookArrayForExcluded(value);
  15882. },
  15883. enumerable: true,
  15884. configurable: true
  15885. });
  15886. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15887. get: function () {
  15888. return this._excludeWithLayerMask;
  15889. },
  15890. set: function (value) {
  15891. this._excludeWithLayerMask = value;
  15892. this._resyncMeshes();
  15893. },
  15894. enumerable: true,
  15895. configurable: true
  15896. });
  15897. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15898. get: function () {
  15899. return this._includeOnlyWithLayerMask;
  15900. },
  15901. set: function (value) {
  15902. this._includeOnlyWithLayerMask = value;
  15903. this._resyncMeshes();
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Light.prototype, "lightmapMode", {
  15909. get: function () {
  15910. return this._lightmapMode;
  15911. },
  15912. set: function (value) {
  15913. if (this._lightmapMode === value) {
  15914. return;
  15915. }
  15916. this._lightmapMode = value;
  15917. this._markMeshesAsLightDirty();
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Light.prototype._buildUniformLayout = function () {
  15923. // Overridden
  15924. };
  15925. /**
  15926. * Returns the string "Light".
  15927. */
  15928. Light.prototype.getClassName = function () {
  15929. return "Light";
  15930. };
  15931. /**
  15932. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15933. */
  15934. Light.prototype.toString = function (fullDetails) {
  15935. var ret = "Name: " + this.name;
  15936. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15937. if (this.animations) {
  15938. for (var i = 0; i < this.animations.length; i++) {
  15939. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15940. }
  15941. }
  15942. if (fullDetails) {
  15943. }
  15944. return ret;
  15945. };
  15946. /**
  15947. * Set the enabled state of this node.
  15948. * @param {boolean} value - the new enabled state
  15949. * @see isEnabled
  15950. */
  15951. Light.prototype.setEnabled = function (value) {
  15952. _super.prototype.setEnabled.call(this, value);
  15953. this._resyncMeshes();
  15954. };
  15955. /**
  15956. * Returns the Light associated shadow generator.
  15957. */
  15958. Light.prototype.getShadowGenerator = function () {
  15959. return this._shadowGenerator;
  15960. };
  15961. /**
  15962. * Returns a Vector3, the absolute light position in the World.
  15963. */
  15964. Light.prototype.getAbsolutePosition = function () {
  15965. return BABYLON.Vector3.Zero();
  15966. };
  15967. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15968. };
  15969. Light.prototype._getWorldMatrix = function () {
  15970. return BABYLON.Matrix.Identity();
  15971. };
  15972. /**
  15973. * Boolean : True if the light will affect the passed mesh.
  15974. */
  15975. Light.prototype.canAffectMesh = function (mesh) {
  15976. if (!mesh) {
  15977. return true;
  15978. }
  15979. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15980. return false;
  15981. }
  15982. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15983. return false;
  15984. }
  15985. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15986. return false;
  15987. }
  15988. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15989. return false;
  15990. }
  15991. return true;
  15992. };
  15993. /**
  15994. * Returns the light World matrix.
  15995. */
  15996. Light.prototype.getWorldMatrix = function () {
  15997. this._currentRenderId = this.getScene().getRenderId();
  15998. var worldMatrix = this._getWorldMatrix();
  15999. if (this.parent && this.parent.getWorldMatrix) {
  16000. if (!this._parentedWorldMatrix) {
  16001. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16002. }
  16003. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16004. this._markSyncedWithParent();
  16005. return this._parentedWorldMatrix;
  16006. }
  16007. return worldMatrix;
  16008. };
  16009. /**
  16010. * Sort function to order lights for rendering.
  16011. * @param a First Light object to compare to second.
  16012. * @param b Second Light object to compare first.
  16013. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16014. */
  16015. Light.compareLightsPriority = function (a, b) {
  16016. //shadow-casting lights have priority over non-shadow-casting lights
  16017. //the renderPrioirty is a secondary sort criterion
  16018. if (a.shadowEnabled !== b.shadowEnabled) {
  16019. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16020. }
  16021. return b.renderPriority - a.renderPriority;
  16022. };
  16023. /**
  16024. * Disposes the light.
  16025. */
  16026. Light.prototype.dispose = function () {
  16027. if (this._shadowGenerator) {
  16028. this._shadowGenerator.dispose();
  16029. this._shadowGenerator = null;
  16030. }
  16031. // Animations
  16032. this.getScene().stopAnimation(this);
  16033. // Remove from meshes
  16034. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16035. var mesh = _a[_i];
  16036. mesh._removeLightSource(this);
  16037. }
  16038. this._uniformBuffer.dispose();
  16039. // Remove from scene
  16040. this.getScene().removeLight(this);
  16041. _super.prototype.dispose.call(this);
  16042. };
  16043. /**
  16044. * Returns the light type ID (integer).
  16045. */
  16046. Light.prototype.getTypeID = function () {
  16047. return 0;
  16048. };
  16049. /**
  16050. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16051. */
  16052. Light.prototype.getScaledIntensity = function () {
  16053. return this._photometricScale * this.intensity;
  16054. };
  16055. /**
  16056. * Returns a new Light object, named "name", from the current one.
  16057. */
  16058. Light.prototype.clone = function (name) {
  16059. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16060. if (!constructor) {
  16061. return null;
  16062. }
  16063. return BABYLON.SerializationHelper.Clone(constructor, this);
  16064. };
  16065. /**
  16066. * Serializes the current light into a Serialization object.
  16067. * Returns the serialized object.
  16068. */
  16069. Light.prototype.serialize = function () {
  16070. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16071. // Type
  16072. serializationObject.type = this.getTypeID();
  16073. // Parent
  16074. if (this.parent) {
  16075. serializationObject.parentId = this.parent.id;
  16076. }
  16077. // Inclusion / exclusions
  16078. if (this.excludedMeshes.length > 0) {
  16079. serializationObject.excludedMeshesIds = [];
  16080. this.excludedMeshes.forEach(function (mesh) {
  16081. serializationObject.excludedMeshesIds.push(mesh.id);
  16082. });
  16083. }
  16084. if (this.includedOnlyMeshes.length > 0) {
  16085. serializationObject.includedOnlyMeshesIds = [];
  16086. this.includedOnlyMeshes.forEach(function (mesh) {
  16087. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16088. });
  16089. }
  16090. // Animations
  16091. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16092. serializationObject.ranges = this.serializeAnimationRanges();
  16093. return serializationObject;
  16094. };
  16095. /**
  16096. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16097. * This new light is named "name" and added to the passed scene.
  16098. */
  16099. Light.GetConstructorFromName = function (type, name, scene) {
  16100. switch (type) {
  16101. case 0:
  16102. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16103. case 1:
  16104. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16105. case 2:
  16106. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16107. case 3:
  16108. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16109. }
  16110. return null;
  16111. };
  16112. /**
  16113. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16114. */
  16115. Light.Parse = function (parsedLight, scene) {
  16116. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16117. if (!constructor) {
  16118. return null;
  16119. }
  16120. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16121. // Inclusion / exclusions
  16122. if (parsedLight.excludedMeshesIds) {
  16123. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16124. }
  16125. if (parsedLight.includedOnlyMeshesIds) {
  16126. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16127. }
  16128. // Parent
  16129. if (parsedLight.parentId) {
  16130. light._waitingParentId = parsedLight.parentId;
  16131. }
  16132. // Animations
  16133. if (parsedLight.animations) {
  16134. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16135. var parsedAnimation = parsedLight.animations[animationIndex];
  16136. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16137. }
  16138. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16139. }
  16140. if (parsedLight.autoAnimate) {
  16141. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16142. }
  16143. return light;
  16144. };
  16145. Light.prototype._hookArrayForExcluded = function (array) {
  16146. var _this = this;
  16147. var oldPush = array.push;
  16148. array.push = function () {
  16149. var items = [];
  16150. for (var _i = 0; _i < arguments.length; _i++) {
  16151. items[_i] = arguments[_i];
  16152. }
  16153. var result = oldPush.apply(array, items);
  16154. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16155. var item = items_1[_a];
  16156. item._resyncLighSource(_this);
  16157. }
  16158. return result;
  16159. };
  16160. var oldSplice = array.splice;
  16161. array.splice = function (index, deleteCount) {
  16162. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16163. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16164. var item = deleted_1[_i];
  16165. item._resyncLighSource(_this);
  16166. }
  16167. return deleted;
  16168. };
  16169. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16170. var item = array_1[_i];
  16171. item._resyncLighSource(this);
  16172. }
  16173. };
  16174. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16175. var _this = this;
  16176. var oldPush = array.push;
  16177. array.push = function () {
  16178. var items = [];
  16179. for (var _i = 0; _i < arguments.length; _i++) {
  16180. items[_i] = arguments[_i];
  16181. }
  16182. var result = oldPush.apply(array, items);
  16183. _this._resyncMeshes();
  16184. return result;
  16185. };
  16186. var oldSplice = array.splice;
  16187. array.splice = function (index, deleteCount) {
  16188. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16189. _this._resyncMeshes();
  16190. return deleted;
  16191. };
  16192. this._resyncMeshes();
  16193. };
  16194. Light.prototype._resyncMeshes = function () {
  16195. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16196. var mesh = _a[_i];
  16197. mesh._resyncLighSource(this);
  16198. }
  16199. };
  16200. Light.prototype._markMeshesAsLightDirty = function () {
  16201. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16202. var mesh = _a[_i];
  16203. if (mesh._lightSources.indexOf(this) !== -1) {
  16204. mesh._markSubMeshesAsLightDirty();
  16205. }
  16206. }
  16207. };
  16208. /**
  16209. * Recomputes the cached photometric scale if needed.
  16210. */
  16211. Light.prototype._computePhotometricScale = function () {
  16212. this._photometricScale = this._getPhotometricScale();
  16213. this.getScene().resetCachedMaterial();
  16214. };
  16215. /**
  16216. * Returns the Photometric Scale according to the light type and intensity mode.
  16217. */
  16218. Light.prototype._getPhotometricScale = function () {
  16219. var photometricScale = 0.0;
  16220. var lightTypeID = this.getTypeID();
  16221. //get photometric mode
  16222. var photometricMode = this.intensityMode;
  16223. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16224. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16225. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16226. }
  16227. else {
  16228. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16229. }
  16230. }
  16231. //compute photometric scale
  16232. switch (lightTypeID) {
  16233. case Light.LIGHTTYPEID_POINTLIGHT:
  16234. case Light.LIGHTTYPEID_SPOTLIGHT:
  16235. switch (photometricMode) {
  16236. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16237. photometricScale = 1.0 / (4.0 * Math.PI);
  16238. break;
  16239. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16240. photometricScale = 1.0;
  16241. break;
  16242. case Light.INTENSITYMODE_LUMINANCE:
  16243. photometricScale = this.radius * this.radius;
  16244. break;
  16245. }
  16246. break;
  16247. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16248. switch (photometricMode) {
  16249. case Light.INTENSITYMODE_ILLUMINANCE:
  16250. photometricScale = 1.0;
  16251. break;
  16252. case Light.INTENSITYMODE_LUMINANCE:
  16253. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16254. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16255. var apexAngleRadians = this.radius;
  16256. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16257. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16258. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16259. photometricScale = solidAngle;
  16260. break;
  16261. }
  16262. break;
  16263. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16264. // No fall off in hemisperic light.
  16265. photometricScale = 1.0;
  16266. break;
  16267. }
  16268. return photometricScale;
  16269. };
  16270. Light.prototype._reorderLightsInScene = function () {
  16271. var scene = this.getScene();
  16272. if (this._renderPriority != 0) {
  16273. scene.requireLightSorting = true;
  16274. }
  16275. this.getScene().sortLightsByPriority();
  16276. };
  16277. //lightmapMode Consts
  16278. Light._LIGHTMAP_DEFAULT = 0;
  16279. Light._LIGHTMAP_SPECULAR = 1;
  16280. Light._LIGHTMAP_SHADOWSONLY = 2;
  16281. // Intensity Mode Consts
  16282. Light._INTENSITYMODE_AUTOMATIC = 0;
  16283. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16284. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16285. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16286. Light._INTENSITYMODE_LUMINANCE = 4;
  16287. // Light types ids const.
  16288. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16289. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16290. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16291. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16292. __decorate([
  16293. BABYLON.serializeAsColor3()
  16294. ], Light.prototype, "diffuse", void 0);
  16295. __decorate([
  16296. BABYLON.serializeAsColor3()
  16297. ], Light.prototype, "specular", void 0);
  16298. __decorate([
  16299. BABYLON.serialize()
  16300. ], Light.prototype, "intensity", void 0);
  16301. __decorate([
  16302. BABYLON.serialize()
  16303. ], Light.prototype, "range", void 0);
  16304. __decorate([
  16305. BABYLON.serialize()
  16306. ], Light.prototype, "intensityMode", null);
  16307. __decorate([
  16308. BABYLON.serialize()
  16309. ], Light.prototype, "radius", null);
  16310. __decorate([
  16311. BABYLON.serialize()
  16312. ], Light.prototype, "_renderPriority", void 0);
  16313. __decorate([
  16314. BABYLON.expandToProperty("_reorderLightsInScene")
  16315. ], Light.prototype, "renderPriority", void 0);
  16316. __decorate([
  16317. BABYLON.serialize()
  16318. ], Light.prototype, "shadowEnabled", void 0);
  16319. __decorate([
  16320. BABYLON.serialize("excludeWithLayerMask")
  16321. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16322. __decorate([
  16323. BABYLON.serialize("includeOnlyWithLayerMask")
  16324. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16325. __decorate([
  16326. BABYLON.serialize("lightmapMode")
  16327. ], Light.prototype, "_lightmapMode", void 0);
  16328. return Light;
  16329. }(BABYLON.Node));
  16330. BABYLON.Light = Light;
  16331. })(BABYLON || (BABYLON = {}));
  16332. //# sourceMappingURL=babylon.light.js.map
  16333. var BABYLON;
  16334. (function (BABYLON) {
  16335. var Camera = /** @class */ (function (_super) {
  16336. __extends(Camera, _super);
  16337. function Camera(name, position, scene) {
  16338. var _this = _super.call(this, name, scene) || this;
  16339. _this.upVector = BABYLON.Vector3.Up();
  16340. _this.orthoLeft = null;
  16341. _this.orthoRight = null;
  16342. _this.orthoBottom = null;
  16343. _this.orthoTop = null;
  16344. _this.fov = 0.8;
  16345. _this.minZ = 1;
  16346. _this.maxZ = 10000.0;
  16347. _this.inertia = 0.9;
  16348. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16349. _this.isIntermediate = false;
  16350. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16351. _this.layerMask = 0x0FFFFFFF;
  16352. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16353. // Camera rig members
  16354. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16355. _this._rigCameras = new Array();
  16356. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16357. _this._skipRendering = false;
  16358. _this.customRenderTargets = new Array();
  16359. // Observables
  16360. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16361. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16362. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16363. _this.onRestoreStateObservable = new BABYLON.Observable();
  16364. // Cache
  16365. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16366. _this._projectionMatrix = new BABYLON.Matrix();
  16367. _this._doNotComputeProjectionMatrix = false;
  16368. _this._postProcesses = new Array();
  16369. _this._transformMatrix = BABYLON.Matrix.Zero();
  16370. _this._activeMeshes = new BABYLON.SmartArray(256);
  16371. _this._globalPosition = BABYLON.Vector3.Zero();
  16372. _this._refreshFrustumPlanes = true;
  16373. _this.getScene().addCamera(_this);
  16374. if (!_this.getScene().activeCamera) {
  16375. _this.getScene().activeCamera = _this;
  16376. }
  16377. _this.position = position;
  16378. return _this;
  16379. }
  16380. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16381. get: function () {
  16382. return Camera._PERSPECTIVE_CAMERA;
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16388. get: function () {
  16389. return Camera._ORTHOGRAPHIC_CAMERA;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16395. get: function () {
  16396. return Camera._FOVMODE_VERTICAL_FIXED;
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16402. get: function () {
  16403. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16409. get: function () {
  16410. return Camera._RIG_MODE_NONE;
  16411. },
  16412. enumerable: true,
  16413. configurable: true
  16414. });
  16415. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16416. get: function () {
  16417. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16418. },
  16419. enumerable: true,
  16420. configurable: true
  16421. });
  16422. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16423. get: function () {
  16424. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16430. get: function () {
  16431. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16437. get: function () {
  16438. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16444. get: function () {
  16445. return Camera._RIG_MODE_VR;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16451. get: function () {
  16452. return Camera._RIG_MODE_WEBVR;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. /**
  16458. * Store current camera state (fov, position, etc..)
  16459. */
  16460. Camera.prototype.storeState = function () {
  16461. this._stateStored = true;
  16462. this._storedFov = this.fov;
  16463. return this;
  16464. };
  16465. /**
  16466. * Restores the camera state values if it has been stored. You must call storeState() first
  16467. */
  16468. Camera.prototype._restoreStateValues = function () {
  16469. if (!this._stateStored) {
  16470. return false;
  16471. }
  16472. this.fov = this._storedFov;
  16473. return true;
  16474. };
  16475. /**
  16476. * Restored camera state. You must call storeState() first
  16477. */
  16478. Camera.prototype.restoreState = function () {
  16479. if (this._restoreStateValues()) {
  16480. this.onRestoreStateObservable.notifyObservers(this);
  16481. return true;
  16482. }
  16483. return false;
  16484. };
  16485. Camera.prototype.getClassName = function () {
  16486. return "Camera";
  16487. };
  16488. /**
  16489. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16490. */
  16491. Camera.prototype.toString = function (fullDetails) {
  16492. var ret = "Name: " + this.name;
  16493. ret += ", type: " + this.getClassName();
  16494. if (this.animations) {
  16495. for (var i = 0; i < this.animations.length; i++) {
  16496. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16497. }
  16498. }
  16499. if (fullDetails) {
  16500. }
  16501. return ret;
  16502. };
  16503. Object.defineProperty(Camera.prototype, "globalPosition", {
  16504. get: function () {
  16505. return this._globalPosition;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. Camera.prototype.getActiveMeshes = function () {
  16511. return this._activeMeshes;
  16512. };
  16513. Camera.prototype.isActiveMesh = function (mesh) {
  16514. return (this._activeMeshes.indexOf(mesh) !== -1);
  16515. };
  16516. //Cache
  16517. Camera.prototype._initCache = function () {
  16518. _super.prototype._initCache.call(this);
  16519. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16520. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16521. this._cache.mode = undefined;
  16522. this._cache.minZ = undefined;
  16523. this._cache.maxZ = undefined;
  16524. this._cache.fov = undefined;
  16525. this._cache.fovMode = undefined;
  16526. this._cache.aspectRatio = undefined;
  16527. this._cache.orthoLeft = undefined;
  16528. this._cache.orthoRight = undefined;
  16529. this._cache.orthoBottom = undefined;
  16530. this._cache.orthoTop = undefined;
  16531. this._cache.renderWidth = undefined;
  16532. this._cache.renderHeight = undefined;
  16533. };
  16534. Camera.prototype._updateCache = function (ignoreParentClass) {
  16535. if (!ignoreParentClass) {
  16536. _super.prototype._updateCache.call(this);
  16537. }
  16538. this._cache.position.copyFrom(this.position);
  16539. this._cache.upVector.copyFrom(this.upVector);
  16540. };
  16541. // Synchronized
  16542. Camera.prototype._isSynchronized = function () {
  16543. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16544. };
  16545. Camera.prototype._isSynchronizedViewMatrix = function () {
  16546. if (!_super.prototype._isSynchronized.call(this))
  16547. return false;
  16548. return this._cache.position.equals(this.position)
  16549. && this._cache.upVector.equals(this.upVector)
  16550. && this.isSynchronizedWithParent();
  16551. };
  16552. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16553. var check = this._cache.mode === this.mode
  16554. && this._cache.minZ === this.minZ
  16555. && this._cache.maxZ === this.maxZ;
  16556. if (!check) {
  16557. return false;
  16558. }
  16559. var engine = this.getEngine();
  16560. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16561. check = this._cache.fov === this.fov
  16562. && this._cache.fovMode === this.fovMode
  16563. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16564. }
  16565. else {
  16566. check = this._cache.orthoLeft === this.orthoLeft
  16567. && this._cache.orthoRight === this.orthoRight
  16568. && this._cache.orthoBottom === this.orthoBottom
  16569. && this._cache.orthoTop === this.orthoTop
  16570. && this._cache.renderWidth === engine.getRenderWidth()
  16571. && this._cache.renderHeight === engine.getRenderHeight();
  16572. }
  16573. return check;
  16574. };
  16575. // Controls
  16576. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16577. };
  16578. Camera.prototype.detachControl = function (element) {
  16579. };
  16580. Camera.prototype.update = function () {
  16581. this._checkInputs();
  16582. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16583. this._updateRigCameras();
  16584. }
  16585. };
  16586. Camera.prototype._checkInputs = function () {
  16587. this.onAfterCheckInputsObservable.notifyObservers(this);
  16588. };
  16589. Object.defineProperty(Camera.prototype, "rigCameras", {
  16590. get: function () {
  16591. return this._rigCameras;
  16592. },
  16593. enumerable: true,
  16594. configurable: true
  16595. });
  16596. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16597. get: function () {
  16598. return this._rigPostProcess;
  16599. },
  16600. enumerable: true,
  16601. configurable: true
  16602. });
  16603. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16604. // invalidate framebuffer
  16605. if (this._postProcesses.length > 0) {
  16606. this._postProcesses[0].markTextureDirty();
  16607. }
  16608. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16609. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16610. var cam = this._rigCameras[i];
  16611. var rigPostProcess = cam._rigPostProcess;
  16612. // for VR rig, there does not have to be a post process
  16613. if (rigPostProcess) {
  16614. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16615. if (isPass) {
  16616. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16617. cam.isIntermediate = this._postProcesses.length === 0;
  16618. }
  16619. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16620. rigPostProcess.markTextureDirty();
  16621. }
  16622. else {
  16623. cam._postProcesses = this._postProcesses.slice(0);
  16624. }
  16625. }
  16626. };
  16627. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16628. if (insertAt === void 0) { insertAt = null; }
  16629. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16630. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16631. return 0;
  16632. }
  16633. if (insertAt == null || insertAt < 0) {
  16634. this._postProcesses.push(postProcess);
  16635. }
  16636. else {
  16637. this._postProcesses.splice(insertAt, 0, postProcess);
  16638. }
  16639. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16640. return this._postProcesses.indexOf(postProcess);
  16641. };
  16642. Camera.prototype.detachPostProcess = function (postProcess) {
  16643. var idx = this._postProcesses.indexOf(postProcess);
  16644. if (idx !== -1) {
  16645. this._postProcesses.splice(idx, 1);
  16646. }
  16647. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16648. };
  16649. Camera.prototype.getWorldMatrix = function () {
  16650. if (!this._worldMatrix) {
  16651. this._worldMatrix = BABYLON.Matrix.Identity();
  16652. }
  16653. var viewMatrix = this.getViewMatrix();
  16654. viewMatrix.invertToRef(this._worldMatrix);
  16655. return this._worldMatrix;
  16656. };
  16657. Camera.prototype._getViewMatrix = function () {
  16658. return BABYLON.Matrix.Identity();
  16659. };
  16660. Camera.prototype.getViewMatrix = function (force) {
  16661. if (!force && this._isSynchronizedViewMatrix()) {
  16662. return this._computedViewMatrix;
  16663. }
  16664. this.updateCache();
  16665. this._computedViewMatrix = this._getViewMatrix();
  16666. this._currentRenderId = this.getScene().getRenderId();
  16667. this._refreshFrustumPlanes = true;
  16668. if (!this.parent || !this.parent.getWorldMatrix) {
  16669. this._globalPosition.copyFrom(this.position);
  16670. }
  16671. else {
  16672. if (!this._worldMatrix) {
  16673. this._worldMatrix = BABYLON.Matrix.Identity();
  16674. }
  16675. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16676. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16677. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16678. this._computedViewMatrix.invert();
  16679. this._markSyncedWithParent();
  16680. }
  16681. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16682. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16683. }
  16684. this.onViewMatrixChangedObservable.notifyObservers(this);
  16685. return this._computedViewMatrix;
  16686. };
  16687. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16688. this._doNotComputeProjectionMatrix = true;
  16689. if (projection !== undefined) {
  16690. this._projectionMatrix = projection;
  16691. }
  16692. };
  16693. ;
  16694. Camera.prototype.unfreezeProjectionMatrix = function () {
  16695. this._doNotComputeProjectionMatrix = false;
  16696. };
  16697. ;
  16698. Camera.prototype.getProjectionMatrix = function (force) {
  16699. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16700. return this._projectionMatrix;
  16701. }
  16702. // Cache
  16703. this._cache.mode = this.mode;
  16704. this._cache.minZ = this.minZ;
  16705. this._cache.maxZ = this.maxZ;
  16706. // Matrix
  16707. this._refreshFrustumPlanes = true;
  16708. var engine = this.getEngine();
  16709. var scene = this.getScene();
  16710. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16711. this._cache.fov = this.fov;
  16712. this._cache.fovMode = this.fovMode;
  16713. this._cache.aspectRatio = engine.getAspectRatio(this);
  16714. if (this.minZ <= 0) {
  16715. this.minZ = 0.1;
  16716. }
  16717. if (scene.useRightHandedSystem) {
  16718. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16719. }
  16720. else {
  16721. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16722. }
  16723. }
  16724. else {
  16725. var halfWidth = engine.getRenderWidth() / 2.0;
  16726. var halfHeight = engine.getRenderHeight() / 2.0;
  16727. if (scene.useRightHandedSystem) {
  16728. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16729. }
  16730. else {
  16731. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16732. }
  16733. this._cache.orthoLeft = this.orthoLeft;
  16734. this._cache.orthoRight = this.orthoRight;
  16735. this._cache.orthoBottom = this.orthoBottom;
  16736. this._cache.orthoTop = this.orthoTop;
  16737. this._cache.renderWidth = engine.getRenderWidth();
  16738. this._cache.renderHeight = engine.getRenderHeight();
  16739. }
  16740. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16741. return this._projectionMatrix;
  16742. };
  16743. Camera.prototype.getTranformationMatrix = function () {
  16744. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16745. return this._transformMatrix;
  16746. };
  16747. Camera.prototype.updateFrustumPlanes = function () {
  16748. if (!this._refreshFrustumPlanes) {
  16749. return;
  16750. }
  16751. this.getTranformationMatrix();
  16752. if (!this._frustumPlanes) {
  16753. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16754. }
  16755. else {
  16756. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16757. }
  16758. this._refreshFrustumPlanes = false;
  16759. };
  16760. Camera.prototype.isInFrustum = function (target) {
  16761. this.updateFrustumPlanes();
  16762. return target.isInFrustum(this._frustumPlanes);
  16763. };
  16764. Camera.prototype.isCompletelyInFrustum = function (target) {
  16765. this.updateFrustumPlanes();
  16766. return target.isCompletelyInFrustum(this._frustumPlanes);
  16767. };
  16768. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16769. if (length === void 0) { length = 100; }
  16770. if (!transform) {
  16771. transform = this.getWorldMatrix();
  16772. }
  16773. if (!origin) {
  16774. origin = this.position;
  16775. }
  16776. var forward = new BABYLON.Vector3(0, 0, 1);
  16777. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16778. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16779. return new BABYLON.Ray(origin, direction, length);
  16780. };
  16781. Camera.prototype.dispose = function () {
  16782. // Observables
  16783. this.onViewMatrixChangedObservable.clear();
  16784. this.onProjectionMatrixChangedObservable.clear();
  16785. this.onAfterCheckInputsObservable.clear();
  16786. this.onRestoreStateObservable.clear();
  16787. // Inputs
  16788. if (this.inputs) {
  16789. this.inputs.clear();
  16790. }
  16791. // Animations
  16792. this.getScene().stopAnimation(this);
  16793. // Remove from scene
  16794. this.getScene().removeCamera(this);
  16795. while (this._rigCameras.length > 0) {
  16796. var camera = this._rigCameras.pop();
  16797. if (camera) {
  16798. camera.dispose();
  16799. }
  16800. }
  16801. // Postprocesses
  16802. if (this._rigPostProcess) {
  16803. this._rigPostProcess.dispose(this);
  16804. this._rigPostProcess = null;
  16805. this._postProcesses = [];
  16806. }
  16807. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16808. this._rigPostProcess = null;
  16809. this._postProcesses = [];
  16810. }
  16811. else {
  16812. var i = this._postProcesses.length;
  16813. while (--i >= 0) {
  16814. this._postProcesses[i].dispose(this);
  16815. }
  16816. }
  16817. // Render targets
  16818. var i = this.customRenderTargets.length;
  16819. while (--i >= 0) {
  16820. this.customRenderTargets[i].dispose();
  16821. }
  16822. this.customRenderTargets = [];
  16823. // Active Meshes
  16824. this._activeMeshes.dispose();
  16825. _super.prototype.dispose.call(this);
  16826. };
  16827. Object.defineProperty(Camera.prototype, "leftCamera", {
  16828. // ---- Camera rigs section ----
  16829. get: function () {
  16830. if (this._rigCameras.length < 1) {
  16831. return null;
  16832. }
  16833. return this._rigCameras[0];
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. Object.defineProperty(Camera.prototype, "rightCamera", {
  16839. get: function () {
  16840. if (this._rigCameras.length < 2) {
  16841. return null;
  16842. }
  16843. return this._rigCameras[1];
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Camera.prototype.getLeftTarget = function () {
  16849. if (this._rigCameras.length < 1) {
  16850. return null;
  16851. }
  16852. return this._rigCameras[0].getTarget();
  16853. };
  16854. Camera.prototype.getRightTarget = function () {
  16855. if (this._rigCameras.length < 2) {
  16856. return null;
  16857. }
  16858. return this._rigCameras[1].getTarget();
  16859. };
  16860. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16861. if (this.cameraRigMode === mode) {
  16862. return;
  16863. }
  16864. while (this._rigCameras.length > 0) {
  16865. var camera = this._rigCameras.pop();
  16866. if (camera) {
  16867. camera.dispose();
  16868. }
  16869. }
  16870. this.cameraRigMode = mode;
  16871. this._cameraRigParams = {};
  16872. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16873. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16874. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16875. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16876. // create the rig cameras, unless none
  16877. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16878. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16879. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16880. if (leftCamera && rightCamera) {
  16881. this._rigCameras.push(leftCamera);
  16882. this._rigCameras.push(rightCamera);
  16883. }
  16884. }
  16885. switch (this.cameraRigMode) {
  16886. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16887. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16888. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16889. break;
  16890. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16891. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16892. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16893. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16894. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16895. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16896. break;
  16897. case Camera.RIG_MODE_VR:
  16898. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16899. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16900. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16901. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16902. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16903. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16904. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16905. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16906. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16907. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16908. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16909. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16910. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16911. if (metrics.compensateDistortion) {
  16912. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16913. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16914. }
  16915. break;
  16916. case Camera.RIG_MODE_WEBVR:
  16917. if (rigParams.vrDisplay) {
  16918. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16919. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16920. //Left eye
  16921. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16922. this._rigCameras[0].setCameraRigParameter("left", true);
  16923. //leaving this for future reference
  16924. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16925. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16926. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16927. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16928. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16929. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16930. this._rigCameras[0].parent = this;
  16931. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16932. //Right eye
  16933. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16934. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16935. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16936. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16937. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16938. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16939. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16940. this._rigCameras[1].parent = this;
  16941. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16942. if (Camera.UseAlternateWebVRRendering) {
  16943. this._rigCameras[1]._skipRendering = true;
  16944. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16945. }
  16946. }
  16947. break;
  16948. }
  16949. this._cascadePostProcessesToRigCams();
  16950. this.update();
  16951. };
  16952. Camera.prototype._getVRProjectionMatrix = function () {
  16953. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16954. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16955. return this._projectionMatrix;
  16956. };
  16957. Camera.prototype._updateCameraRotationMatrix = function () {
  16958. //Here for WebVR
  16959. };
  16960. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16961. //Here for WebVR
  16962. };
  16963. /**
  16964. * This function MUST be overwritten by the different WebVR cameras available.
  16965. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16966. */
  16967. Camera.prototype._getWebVRProjectionMatrix = function () {
  16968. return BABYLON.Matrix.Identity();
  16969. };
  16970. /**
  16971. * This function MUST be overwritten by the different WebVR cameras available.
  16972. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16973. */
  16974. Camera.prototype._getWebVRViewMatrix = function () {
  16975. return BABYLON.Matrix.Identity();
  16976. };
  16977. Camera.prototype.setCameraRigParameter = function (name, value) {
  16978. if (!this._cameraRigParams) {
  16979. this._cameraRigParams = {};
  16980. }
  16981. this._cameraRigParams[name] = value;
  16982. //provisionnally:
  16983. if (name === "interaxialDistance") {
  16984. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16985. }
  16986. };
  16987. /**
  16988. * needs to be overridden by children so sub has required properties to be copied
  16989. */
  16990. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16991. return null;
  16992. };
  16993. /**
  16994. * May need to be overridden by children
  16995. */
  16996. Camera.prototype._updateRigCameras = function () {
  16997. for (var i = 0; i < this._rigCameras.length; i++) {
  16998. this._rigCameras[i].minZ = this.minZ;
  16999. this._rigCameras[i].maxZ = this.maxZ;
  17000. this._rigCameras[i].fov = this.fov;
  17001. }
  17002. // only update viewport when ANAGLYPH
  17003. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17004. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17005. }
  17006. };
  17007. Camera.prototype._setupInputs = function () {
  17008. };
  17009. Camera.prototype.serialize = function () {
  17010. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17011. // Type
  17012. serializationObject.type = this.getClassName();
  17013. // Parent
  17014. if (this.parent) {
  17015. serializationObject.parentId = this.parent.id;
  17016. }
  17017. if (this.inputs) {
  17018. this.inputs.serialize(serializationObject);
  17019. }
  17020. // Animations
  17021. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17022. serializationObject.ranges = this.serializeAnimationRanges();
  17023. return serializationObject;
  17024. };
  17025. Camera.prototype.clone = function (name) {
  17026. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17027. };
  17028. Camera.prototype.getDirection = function (localAxis) {
  17029. var result = BABYLON.Vector3.Zero();
  17030. this.getDirectionToRef(localAxis, result);
  17031. return result;
  17032. };
  17033. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17034. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17035. };
  17036. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17037. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17038. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17039. switch (type) {
  17040. case "ArcRotateCamera":
  17041. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17042. case "DeviceOrientationCamera":
  17043. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17044. case "FollowCamera":
  17045. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17046. case "ArcFollowCamera":
  17047. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17048. case "GamepadCamera":
  17049. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17050. case "TouchCamera":
  17051. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17052. case "VirtualJoysticksCamera":
  17053. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17054. case "WebVRFreeCamera":
  17055. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17056. case "WebVRGamepadCamera":
  17057. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17058. case "VRDeviceOrientationFreeCamera":
  17059. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17060. case "VRDeviceOrientationGamepadCamera":
  17061. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17062. case "AnaglyphArcRotateCamera":
  17063. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17064. case "AnaglyphFreeCamera":
  17065. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17066. case "AnaglyphGamepadCamera":
  17067. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17068. case "AnaglyphUniversalCamera":
  17069. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17070. case "StereoscopicArcRotateCamera":
  17071. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17072. case "StereoscopicFreeCamera":
  17073. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17074. case "StereoscopicGamepadCamera":
  17075. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17076. case "StereoscopicUniversalCamera":
  17077. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17078. case "FreeCamera":// Forcing Universal here
  17079. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17080. default:// Universal Camera is the default value
  17081. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17082. }
  17083. };
  17084. Camera.Parse = function (parsedCamera, scene) {
  17085. var type = parsedCamera.type;
  17086. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17087. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17088. // Parent
  17089. if (parsedCamera.parentId) {
  17090. camera._waitingParentId = parsedCamera.parentId;
  17091. }
  17092. //If camera has an input manager, let it parse inputs settings
  17093. if (camera.inputs) {
  17094. camera.inputs.parse(parsedCamera);
  17095. camera._setupInputs();
  17096. }
  17097. if (camera.setPosition) {
  17098. camera.position.copyFromFloats(0, 0, 0);
  17099. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17100. }
  17101. // Target
  17102. if (parsedCamera.target) {
  17103. if (camera.setTarget) {
  17104. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17105. }
  17106. }
  17107. // Apply 3d rig, when found
  17108. if (parsedCamera.cameraRigMode) {
  17109. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17110. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17111. }
  17112. // Animations
  17113. if (parsedCamera.animations) {
  17114. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17115. var parsedAnimation = parsedCamera.animations[animationIndex];
  17116. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17117. }
  17118. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17119. }
  17120. if (parsedCamera.autoAnimate) {
  17121. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17122. }
  17123. return camera;
  17124. };
  17125. // Statics
  17126. Camera._PERSPECTIVE_CAMERA = 0;
  17127. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17128. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17129. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17130. Camera._RIG_MODE_NONE = 0;
  17131. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17132. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17133. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17134. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17135. Camera._RIG_MODE_VR = 20;
  17136. Camera._RIG_MODE_WEBVR = 21;
  17137. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17138. Camera.UseAlternateWebVRRendering = false;
  17139. __decorate([
  17140. BABYLON.serializeAsVector3()
  17141. ], Camera.prototype, "position", void 0);
  17142. __decorate([
  17143. BABYLON.serializeAsVector3()
  17144. ], Camera.prototype, "upVector", void 0);
  17145. __decorate([
  17146. BABYLON.serialize()
  17147. ], Camera.prototype, "orthoLeft", void 0);
  17148. __decorate([
  17149. BABYLON.serialize()
  17150. ], Camera.prototype, "orthoRight", void 0);
  17151. __decorate([
  17152. BABYLON.serialize()
  17153. ], Camera.prototype, "orthoBottom", void 0);
  17154. __decorate([
  17155. BABYLON.serialize()
  17156. ], Camera.prototype, "orthoTop", void 0);
  17157. __decorate([
  17158. BABYLON.serialize()
  17159. ], Camera.prototype, "fov", void 0);
  17160. __decorate([
  17161. BABYLON.serialize()
  17162. ], Camera.prototype, "minZ", void 0);
  17163. __decorate([
  17164. BABYLON.serialize()
  17165. ], Camera.prototype, "maxZ", void 0);
  17166. __decorate([
  17167. BABYLON.serialize()
  17168. ], Camera.prototype, "inertia", void 0);
  17169. __decorate([
  17170. BABYLON.serialize()
  17171. ], Camera.prototype, "mode", void 0);
  17172. __decorate([
  17173. BABYLON.serialize()
  17174. ], Camera.prototype, "layerMask", void 0);
  17175. __decorate([
  17176. BABYLON.serialize()
  17177. ], Camera.prototype, "fovMode", void 0);
  17178. __decorate([
  17179. BABYLON.serialize()
  17180. ], Camera.prototype, "cameraRigMode", void 0);
  17181. __decorate([
  17182. BABYLON.serialize()
  17183. ], Camera.prototype, "interaxialDistance", void 0);
  17184. __decorate([
  17185. BABYLON.serialize()
  17186. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17187. return Camera;
  17188. }(BABYLON.Node));
  17189. BABYLON.Camera = Camera;
  17190. })(BABYLON || (BABYLON = {}));
  17191. //# sourceMappingURL=babylon.camera.js.map
  17192. var BABYLON;
  17193. (function (BABYLON) {
  17194. var RenderingManager = /** @class */ (function () {
  17195. function RenderingManager(scene) {
  17196. this._renderingGroups = new Array();
  17197. this._autoClearDepthStencil = {};
  17198. this._customOpaqueSortCompareFn = {};
  17199. this._customAlphaTestSortCompareFn = {};
  17200. this._customTransparentSortCompareFn = {};
  17201. this._renderinGroupInfo = null;
  17202. this._scene = scene;
  17203. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17204. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17205. }
  17206. }
  17207. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17208. if (depth === void 0) { depth = true; }
  17209. if (stencil === void 0) { stencil = true; }
  17210. if (this._depthStencilBufferAlreadyCleaned) {
  17211. return;
  17212. }
  17213. this._scene.getEngine().clear(null, false, depth, stencil);
  17214. this._depthStencilBufferAlreadyCleaned = true;
  17215. };
  17216. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17217. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17218. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17219. var info = null;
  17220. if (observable) {
  17221. if (!this._renderinGroupInfo) {
  17222. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17223. }
  17224. info = this._renderinGroupInfo;
  17225. info.scene = this._scene;
  17226. info.camera = this._scene.activeCamera;
  17227. }
  17228. // Dispatch sprites
  17229. if (renderSprites) {
  17230. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17231. var manager = this._scene.spriteManagers[index];
  17232. this.dispatchSprites(manager);
  17233. }
  17234. }
  17235. // Render
  17236. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17237. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17238. var renderingGroup = this._renderingGroups[index];
  17239. if (!renderingGroup && !observable)
  17240. continue;
  17241. var renderingGroupMask = 0;
  17242. // Fire PRECLEAR stage
  17243. if (observable && info) {
  17244. renderingGroupMask = Math.pow(2, index);
  17245. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17246. info.renderingGroupId = index;
  17247. observable.notifyObservers(info, renderingGroupMask);
  17248. }
  17249. // Clear depth/stencil if needed
  17250. if (RenderingManager.AUTOCLEAR) {
  17251. var autoClear = this._autoClearDepthStencil[index];
  17252. if (autoClear && autoClear.autoClear) {
  17253. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17254. }
  17255. }
  17256. if (observable && info) {
  17257. // Fire PREOPAQUE stage
  17258. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17259. observable.notifyObservers(info, renderingGroupMask);
  17260. // Fire PRETRANSPARENT stage
  17261. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17262. observable.notifyObservers(info, renderingGroupMask);
  17263. }
  17264. if (renderingGroup)
  17265. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17266. // Fire POSTTRANSPARENT stage
  17267. if (observable && info) {
  17268. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17269. observable.notifyObservers(info, renderingGroupMask);
  17270. }
  17271. }
  17272. };
  17273. RenderingManager.prototype.reset = function () {
  17274. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17275. var renderingGroup = this._renderingGroups[index];
  17276. if (renderingGroup) {
  17277. renderingGroup.prepare();
  17278. }
  17279. }
  17280. };
  17281. RenderingManager.prototype.dispose = function () {
  17282. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17283. var renderingGroup = this._renderingGroups[index];
  17284. if (renderingGroup) {
  17285. renderingGroup.dispose();
  17286. }
  17287. }
  17288. this._renderingGroups.length = 0;
  17289. };
  17290. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17291. if (!this._renderingGroups[renderingGroupId]) {
  17292. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17293. }
  17294. };
  17295. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17296. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17297. this._prepareRenderingGroup(renderingGroupId);
  17298. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17299. };
  17300. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17301. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17302. this._prepareRenderingGroup(renderingGroupId);
  17303. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17304. };
  17305. RenderingManager.prototype.dispatch = function (subMesh) {
  17306. var mesh = subMesh.getMesh();
  17307. var renderingGroupId = mesh.renderingGroupId || 0;
  17308. this._prepareRenderingGroup(renderingGroupId);
  17309. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17310. };
  17311. /**
  17312. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17313. * This allowed control for front to back rendering or reversly depending of the special needs.
  17314. *
  17315. * @param renderingGroupId The rendering group id corresponding to its index
  17316. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17317. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17318. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17319. */
  17320. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17321. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17322. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17323. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17324. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17325. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17326. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17327. if (this._renderingGroups[renderingGroupId]) {
  17328. var group = this._renderingGroups[renderingGroupId];
  17329. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17330. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17331. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17332. }
  17333. };
  17334. /**
  17335. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17336. *
  17337. * @param renderingGroupId The rendering group id corresponding to its index
  17338. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17339. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17340. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17341. */
  17342. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17343. if (depth === void 0) { depth = true; }
  17344. if (stencil === void 0) { stencil = true; }
  17345. this._autoClearDepthStencil[renderingGroupId] = {
  17346. autoClear: autoClearDepthStencil,
  17347. depth: depth,
  17348. stencil: stencil
  17349. };
  17350. };
  17351. /**
  17352. * The max id used for rendering groups (not included)
  17353. */
  17354. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17355. /**
  17356. * The min id used for rendering groups (included)
  17357. */
  17358. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17359. /**
  17360. * Used to globally prevent autoclearing scenes.
  17361. */
  17362. RenderingManager.AUTOCLEAR = true;
  17363. return RenderingManager;
  17364. }());
  17365. BABYLON.RenderingManager = RenderingManager;
  17366. })(BABYLON || (BABYLON = {}));
  17367. //# sourceMappingURL=babylon.renderingManager.js.map
  17368. var BABYLON;
  17369. (function (BABYLON) {
  17370. var RenderingGroup = /** @class */ (function () {
  17371. /**
  17372. * Creates a new rendering group.
  17373. * @param index The rendering group index
  17374. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17375. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17376. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17377. */
  17378. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17379. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17380. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17381. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17382. this.index = index;
  17383. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17384. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17385. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17386. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17387. this._particleSystems = new BABYLON.SmartArray(256);
  17388. this._spriteManagers = new BABYLON.SmartArray(256);
  17389. this._edgesRenderers = new BABYLON.SmartArray(16);
  17390. this._scene = scene;
  17391. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17392. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17393. this.transparentSortCompareFn = transparentSortCompareFn;
  17394. }
  17395. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17396. /**
  17397. * Set the opaque sort comparison function.
  17398. * If null the sub meshes will be render in the order they were created
  17399. */
  17400. set: function (value) {
  17401. this._opaqueSortCompareFn = value;
  17402. if (value) {
  17403. this._renderOpaque = this.renderOpaqueSorted;
  17404. }
  17405. else {
  17406. this._renderOpaque = RenderingGroup.renderUnsorted;
  17407. }
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17413. /**
  17414. * Set the alpha test sort comparison function.
  17415. * If null the sub meshes will be render in the order they were created
  17416. */
  17417. set: function (value) {
  17418. this._alphaTestSortCompareFn = value;
  17419. if (value) {
  17420. this._renderAlphaTest = this.renderAlphaTestSorted;
  17421. }
  17422. else {
  17423. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17424. }
  17425. },
  17426. enumerable: true,
  17427. configurable: true
  17428. });
  17429. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17430. /**
  17431. * Set the transparent sort comparison function.
  17432. * If null the sub meshes will be render in the order they were created
  17433. */
  17434. set: function (value) {
  17435. if (value) {
  17436. this._transparentSortCompareFn = value;
  17437. }
  17438. else {
  17439. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17440. }
  17441. this._renderTransparent = this.renderTransparentSorted;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. /**
  17447. * Render all the sub meshes contained in the group.
  17448. * @param customRenderFunction Used to override the default render behaviour of the group.
  17449. * @returns true if rendered some submeshes.
  17450. */
  17451. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17452. if (customRenderFunction) {
  17453. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17454. return;
  17455. }
  17456. var engine = this._scene.getEngine();
  17457. // Depth only
  17458. if (this._depthOnlySubMeshes.length !== 0) {
  17459. engine.setAlphaTesting(true);
  17460. engine.setColorWrite(false);
  17461. this._renderAlphaTest(this._depthOnlySubMeshes);
  17462. engine.setAlphaTesting(false);
  17463. engine.setColorWrite(true);
  17464. }
  17465. // Opaque
  17466. if (this._opaqueSubMeshes.length !== 0) {
  17467. this._renderOpaque(this._opaqueSubMeshes);
  17468. }
  17469. // Alpha test
  17470. if (this._alphaTestSubMeshes.length !== 0) {
  17471. engine.setAlphaTesting(true);
  17472. this._renderAlphaTest(this._alphaTestSubMeshes);
  17473. engine.setAlphaTesting(false);
  17474. }
  17475. var stencilState = engine.getStencilBuffer();
  17476. engine.setStencilBuffer(false);
  17477. // Sprites
  17478. if (renderSprites) {
  17479. this._renderSprites();
  17480. }
  17481. // Particles
  17482. if (renderParticles) {
  17483. this._renderParticles(activeMeshes);
  17484. }
  17485. if (this.onBeforeTransparentRendering) {
  17486. this.onBeforeTransparentRendering();
  17487. }
  17488. // Transparent
  17489. if (this._transparentSubMeshes.length !== 0) {
  17490. this._renderTransparent(this._transparentSubMeshes);
  17491. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17492. }
  17493. // Set back stencil to false in case it changes before the edge renderer.
  17494. engine.setStencilBuffer(false);
  17495. // Edges
  17496. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17497. this._edgesRenderers.data[edgesRendererIndex].render();
  17498. }
  17499. // Restore Stencil state.
  17500. engine.setStencilBuffer(stencilState);
  17501. };
  17502. /**
  17503. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17504. * @param subMeshes The submeshes to render
  17505. */
  17506. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17507. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17508. };
  17509. /**
  17510. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17511. * @param subMeshes The submeshes to render
  17512. */
  17513. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17514. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17515. };
  17516. /**
  17517. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17518. * @param subMeshes The submeshes to render
  17519. */
  17520. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17521. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17522. };
  17523. /**
  17524. * Renders the submeshes in a specified order.
  17525. * @param subMeshes The submeshes to sort before render
  17526. * @param sortCompareFn The comparison function use to sort
  17527. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17528. * @param transparent Specifies to activate blending if true
  17529. */
  17530. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17531. var subIndex = 0;
  17532. var subMesh;
  17533. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17534. for (; subIndex < subMeshes.length; subIndex++) {
  17535. subMesh = subMeshes.data[subIndex];
  17536. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17537. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17538. }
  17539. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17540. if (sortCompareFn) {
  17541. sortedArray.sort(sortCompareFn);
  17542. }
  17543. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17544. subMesh = sortedArray[subIndex];
  17545. if (transparent) {
  17546. var material = subMesh.getMaterial();
  17547. if (material && material.needDepthPrePass) {
  17548. var engine = material.getScene().getEngine();
  17549. engine.setColorWrite(false);
  17550. engine.setAlphaTesting(true);
  17551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17552. subMesh.render(false);
  17553. engine.setAlphaTesting(false);
  17554. engine.setColorWrite(true);
  17555. }
  17556. }
  17557. subMesh.render(transparent);
  17558. }
  17559. };
  17560. /**
  17561. * Renders the submeshes in the order they were dispatched (no sort applied).
  17562. * @param subMeshes The submeshes to render
  17563. */
  17564. RenderingGroup.renderUnsorted = function (subMeshes) {
  17565. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17566. var submesh = subMeshes.data[subIndex];
  17567. submesh.render(false);
  17568. }
  17569. };
  17570. /**
  17571. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17572. * are rendered back to front if in the same alpha index.
  17573. *
  17574. * @param a The first submesh
  17575. * @param b The second submesh
  17576. * @returns The result of the comparison
  17577. */
  17578. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17579. // Alpha index first
  17580. if (a._alphaIndex > b._alphaIndex) {
  17581. return 1;
  17582. }
  17583. if (a._alphaIndex < b._alphaIndex) {
  17584. return -1;
  17585. }
  17586. // Then distance to camera
  17587. return RenderingGroup.backToFrontSortCompare(a, b);
  17588. };
  17589. /**
  17590. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17591. * are rendered back to front.
  17592. *
  17593. * @param a The first submesh
  17594. * @param b The second submesh
  17595. * @returns The result of the comparison
  17596. */
  17597. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17598. // Then distance to camera
  17599. if (a._distanceToCamera < b._distanceToCamera) {
  17600. return 1;
  17601. }
  17602. if (a._distanceToCamera > b._distanceToCamera) {
  17603. return -1;
  17604. }
  17605. return 0;
  17606. };
  17607. /**
  17608. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17609. * are rendered front to back (prevent overdraw).
  17610. *
  17611. * @param a The first submesh
  17612. * @param b The second submesh
  17613. * @returns The result of the comparison
  17614. */
  17615. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17616. // Then distance to camera
  17617. if (a._distanceToCamera < b._distanceToCamera) {
  17618. return -1;
  17619. }
  17620. if (a._distanceToCamera > b._distanceToCamera) {
  17621. return 1;
  17622. }
  17623. return 0;
  17624. };
  17625. /**
  17626. * Resets the different lists of submeshes to prepare a new frame.
  17627. */
  17628. RenderingGroup.prototype.prepare = function () {
  17629. this._opaqueSubMeshes.reset();
  17630. this._transparentSubMeshes.reset();
  17631. this._alphaTestSubMeshes.reset();
  17632. this._depthOnlySubMeshes.reset();
  17633. this._particleSystems.reset();
  17634. this._spriteManagers.reset();
  17635. this._edgesRenderers.reset();
  17636. };
  17637. RenderingGroup.prototype.dispose = function () {
  17638. this._opaqueSubMeshes.dispose();
  17639. this._transparentSubMeshes.dispose();
  17640. this._alphaTestSubMeshes.dispose();
  17641. this._depthOnlySubMeshes.dispose();
  17642. this._particleSystems.dispose();
  17643. this._spriteManagers.dispose();
  17644. this._edgesRenderers.dispose();
  17645. };
  17646. /**
  17647. * Inserts the submesh in its correct queue depending on its material.
  17648. * @param subMesh The submesh to dispatch
  17649. */
  17650. RenderingGroup.prototype.dispatch = function (subMesh) {
  17651. var material = subMesh.getMaterial();
  17652. var mesh = subMesh.getMesh();
  17653. if (!material) {
  17654. return;
  17655. }
  17656. if (material.needAlphaBlendingForMesh(mesh)) {
  17657. this._transparentSubMeshes.push(subMesh);
  17658. }
  17659. else if (material.needAlphaTesting()) {
  17660. if (material.needDepthPrePass) {
  17661. this._depthOnlySubMeshes.push(subMesh);
  17662. }
  17663. this._alphaTestSubMeshes.push(subMesh);
  17664. }
  17665. else {
  17666. if (material.needDepthPrePass) {
  17667. this._depthOnlySubMeshes.push(subMesh);
  17668. }
  17669. this._opaqueSubMeshes.push(subMesh); // Opaque
  17670. }
  17671. if (mesh._edgesRenderer) {
  17672. this._edgesRenderers.push(mesh._edgesRenderer);
  17673. }
  17674. };
  17675. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17676. this._spriteManagers.push(spriteManager);
  17677. };
  17678. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17679. this._particleSystems.push(particleSystem);
  17680. };
  17681. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17682. if (this._particleSystems.length === 0) {
  17683. return;
  17684. }
  17685. // Particles
  17686. var activeCamera = this._scene.activeCamera;
  17687. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17688. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17689. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17690. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17691. continue;
  17692. }
  17693. var emitter = particleSystem.emitter;
  17694. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17695. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17696. }
  17697. }
  17698. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17699. };
  17700. RenderingGroup.prototype._renderSprites = function () {
  17701. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17702. return;
  17703. }
  17704. // Sprites
  17705. var activeCamera = this._scene.activeCamera;
  17706. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17707. for (var id = 0; id < this._spriteManagers.length; id++) {
  17708. var spriteManager = this._spriteManagers.data[id];
  17709. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17710. spriteManager.render();
  17711. }
  17712. }
  17713. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17714. };
  17715. return RenderingGroup;
  17716. }());
  17717. BABYLON.RenderingGroup = RenderingGroup;
  17718. })(BABYLON || (BABYLON = {}));
  17719. //# sourceMappingURL=babylon.renderingGroup.js.map
  17720. var BABYLON;
  17721. (function (BABYLON) {
  17722. var ClickInfo = /** @class */ (function () {
  17723. function ClickInfo() {
  17724. this._singleClick = false;
  17725. this._doubleClick = false;
  17726. this._hasSwiped = false;
  17727. this._ignore = false;
  17728. }
  17729. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17730. get: function () {
  17731. return this._singleClick;
  17732. },
  17733. set: function (b) {
  17734. this._singleClick = b;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17740. get: function () {
  17741. return this._doubleClick;
  17742. },
  17743. set: function (b) {
  17744. this._doubleClick = b;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17750. get: function () {
  17751. return this._hasSwiped;
  17752. },
  17753. set: function (b) {
  17754. this._hasSwiped = b;
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17760. get: function () {
  17761. return this._ignore;
  17762. },
  17763. set: function (b) {
  17764. this._ignore = b;
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. return ClickInfo;
  17770. }());
  17771. /**
  17772. * This class is used by the onRenderingGroupObservable
  17773. */
  17774. var RenderingGroupInfo = /** @class */ (function () {
  17775. function RenderingGroupInfo() {
  17776. }
  17777. /**
  17778. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17779. * This stage will be fired no matter what
  17780. */
  17781. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17782. /**
  17783. * Called before opaque object are rendered.
  17784. * This stage will be fired only if there's 3D Opaque content to render
  17785. */
  17786. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17787. /**
  17788. * Called after the opaque objects are rendered and before the transparent ones
  17789. * This stage will be fired only if there's 3D transparent content to render
  17790. */
  17791. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17792. /**
  17793. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17794. * This stage will be fired no matter what
  17795. */
  17796. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17797. return RenderingGroupInfo;
  17798. }());
  17799. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17800. /**
  17801. * Represents a scene to be rendered by the engine.
  17802. * @see http://doc.babylonjs.com/page.php?p=21911
  17803. */
  17804. var Scene = /** @class */ (function () {
  17805. /**
  17806. * @constructor
  17807. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17808. */
  17809. function Scene(engine) {
  17810. // Members
  17811. this.autoClear = true;
  17812. this.autoClearDepthAndStencil = true;
  17813. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17814. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17815. this.forceWireframe = false;
  17816. this._forcePointsCloud = false;
  17817. this.forceShowBoundingBoxes = false;
  17818. this.animationsEnabled = true;
  17819. this.constantlyUpdateMeshUnderPointer = false;
  17820. this.hoverCursor = "pointer";
  17821. this.defaultCursor = "";
  17822. /**
  17823. * This is used to call preventDefault() on pointer down
  17824. * in order to block unwanted artifacts like system double clicks
  17825. */
  17826. this.preventDefaultOnPointerDown = true;
  17827. // Metadata
  17828. this.metadata = null;
  17829. /**
  17830. * An event triggered when the scene is disposed.
  17831. * @type {BABYLON.Observable}
  17832. */
  17833. this.onDisposeObservable = new BABYLON.Observable();
  17834. /**
  17835. * An event triggered before rendering the scene (right after animations and physics)
  17836. * @type {BABYLON.Observable}
  17837. */
  17838. this.onBeforeRenderObservable = new BABYLON.Observable();
  17839. /**
  17840. * An event triggered after rendering the scene
  17841. * @type {BABYLON.Observable}
  17842. */
  17843. this.onAfterRenderObservable = new BABYLON.Observable();
  17844. /**
  17845. * An event triggered before animating the scene
  17846. * @type {BABYLON.Observable}
  17847. */
  17848. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17849. /**
  17850. * An event triggered after animations processing
  17851. * @type {BABYLON.Observable}
  17852. */
  17853. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17854. /**
  17855. * An event triggered before draw calls are ready to be sent
  17856. * @type {BABYLON.Observable}
  17857. */
  17858. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17859. /**
  17860. * An event triggered after draw calls have been sent
  17861. * @type {BABYLON.Observable}
  17862. */
  17863. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17864. /**
  17865. * An event triggered when physic simulation is about to be run
  17866. * @type {BABYLON.Observable}
  17867. */
  17868. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17869. /**
  17870. * An event triggered when physic simulation has been done
  17871. * @type {BABYLON.Observable}
  17872. */
  17873. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17874. /**
  17875. * An event triggered when the scene is ready
  17876. * @type {BABYLON.Observable}
  17877. */
  17878. this.onReadyObservable = new BABYLON.Observable();
  17879. /**
  17880. * An event triggered before rendering a camera
  17881. * @type {BABYLON.Observable}
  17882. */
  17883. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17884. /**
  17885. * An event triggered after rendering a camera
  17886. * @type {BABYLON.Observable}
  17887. */
  17888. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17889. /**
  17890. * An event triggered when active meshes evaluation is about to start
  17891. * @type {BABYLON.Observable}
  17892. */
  17893. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17894. /**
  17895. * An event triggered when active meshes evaluation is done
  17896. * @type {BABYLON.Observable}
  17897. */
  17898. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17899. /**
  17900. * An event triggered when particles rendering is about to start
  17901. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17902. * @type {BABYLON.Observable}
  17903. */
  17904. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17905. /**
  17906. * An event triggered when particles rendering is done
  17907. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17908. * @type {BABYLON.Observable}
  17909. */
  17910. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17911. /**
  17912. * An event triggered when sprites rendering is about to start
  17913. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17914. * @type {BABYLON.Observable}
  17915. */
  17916. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17917. /**
  17918. * An event triggered when sprites rendering is done
  17919. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17920. * @type {BABYLON.Observable}
  17921. */
  17922. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17923. /**
  17924. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17925. * @type {BABYLON.Observable}
  17926. */
  17927. this.onDataLoadedObservable = new BABYLON.Observable();
  17928. /**
  17929. * An event triggered when a camera is created
  17930. * @type {BABYLON.Observable}
  17931. */
  17932. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17933. /**
  17934. * An event triggered when a camera is removed
  17935. * @type {BABYLON.Observable}
  17936. */
  17937. this.onCameraRemovedObservable = new BABYLON.Observable();
  17938. /**
  17939. * An event triggered when a light is created
  17940. * @type {BABYLON.Observable}
  17941. */
  17942. this.onNewLightAddedObservable = new BABYLON.Observable();
  17943. /**
  17944. * An event triggered when a light is removed
  17945. * @type {BABYLON.Observable}
  17946. */
  17947. this.onLightRemovedObservable = new BABYLON.Observable();
  17948. /**
  17949. * An event triggered when a geometry is created
  17950. * @type {BABYLON.Observable}
  17951. */
  17952. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17953. /**
  17954. * An event triggered when a geometry is removed
  17955. * @type {BABYLON.Observable}
  17956. */
  17957. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17958. /**
  17959. * An event triggered when a transform node is created
  17960. * @type {BABYLON.Observable}
  17961. */
  17962. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  17963. /**
  17964. * An event triggered when a transform node is removed
  17965. * @type {BABYLON.Observable}
  17966. */
  17967. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  17968. /**
  17969. * An event triggered when a mesh is created
  17970. * @type {BABYLON.Observable}
  17971. */
  17972. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17973. /**
  17974. * An event triggered when a mesh is removed
  17975. * @type {BABYLON.Observable}
  17976. */
  17977. this.onMeshRemovedObservable = new BABYLON.Observable();
  17978. /**
  17979. * An event triggered when render targets are about to be rendered
  17980. * Can happen multiple times per frame.
  17981. * @type {BABYLON.Observable}
  17982. */
  17983. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17984. /**
  17985. * An event triggered when render targets were rendered.
  17986. * Can happen multiple times per frame.
  17987. * @type {BABYLON.Observable}
  17988. */
  17989. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17990. /**
  17991. * An event triggered before calculating deterministic simulation step
  17992. * @type {BABYLON.Observable}
  17993. */
  17994. this.onBeforeStepObservable = new BABYLON.Observable();
  17995. /**
  17996. * An event triggered after calculating deterministic simulation step
  17997. * @type {BABYLON.Observable}
  17998. */
  17999. this.onAfterStepObservable = new BABYLON.Observable();
  18000. /**
  18001. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18002. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18003. * 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)
  18004. */
  18005. this.onRenderingGroupObservable = new BABYLON.Observable();
  18006. // Animations
  18007. this.animations = [];
  18008. /**
  18009. * 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).
  18010. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18011. */
  18012. this.onPrePointerObservable = new BABYLON.Observable();
  18013. /**
  18014. * Observable event triggered each time an input event is received from the rendering canvas
  18015. */
  18016. this.onPointerObservable = new BABYLON.Observable();
  18017. this._meshPickProceed = false;
  18018. this._currentPickResult = null;
  18019. this._previousPickResult = null;
  18020. this._totalPointersPressed = 0;
  18021. this._doubleClickOccured = false;
  18022. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18023. this.cameraToUseForPointers = null;
  18024. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18025. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18026. this._startingPointerTime = 0;
  18027. this._previousStartingPointerTime = 0;
  18028. // Deterministic lockstep
  18029. this._timeAccumulator = 0;
  18030. this._currentStepId = 0;
  18031. this._currentInternalStep = 0;
  18032. // Keyboard
  18033. /**
  18034. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18035. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18036. */
  18037. this.onPreKeyboardObservable = new BABYLON.Observable();
  18038. /**
  18039. * Observable event triggered each time an keyboard event is received from the hosting window
  18040. */
  18041. this.onKeyboardObservable = new BABYLON.Observable();
  18042. // Coordinate system
  18043. /**
  18044. * use right-handed coordinate system on this scene.
  18045. * @type {boolean}
  18046. */
  18047. this._useRightHandedSystem = false;
  18048. // Fog
  18049. this._fogEnabled = true;
  18050. this._fogMode = Scene.FOGMODE_NONE;
  18051. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18052. this.fogDensity = 0.1;
  18053. this.fogStart = 0;
  18054. this.fogEnd = 1000.0;
  18055. // Lights
  18056. /**
  18057. * is shadow enabled on this scene.
  18058. * @type {boolean}
  18059. */
  18060. this._shadowsEnabled = true;
  18061. /**
  18062. * is light enabled on this scene.
  18063. * @type {boolean}
  18064. */
  18065. this._lightsEnabled = true;
  18066. /**
  18067. * All of the lights added to this scene.
  18068. * @see BABYLON.Light
  18069. * @type {BABYLON.Light[]}
  18070. */
  18071. this.lights = new Array();
  18072. // Cameras
  18073. /** All of the cameras added to this scene. */
  18074. this.cameras = new Array();
  18075. /** All of the active cameras added to this scene. */
  18076. this.activeCameras = new Array();
  18077. // Meshes
  18078. /**
  18079. * All of the tranform nodes added to this scene.
  18080. * @see BABYLON.TransformNode
  18081. * @type {BABYLON.TransformNode[]}
  18082. */
  18083. this.transformNodes = new Array();
  18084. /**
  18085. * All of the (abstract) meshes added to this scene.
  18086. * @see BABYLON.AbstractMesh
  18087. * @type {BABYLON.AbstractMesh[]}
  18088. */
  18089. this.meshes = new Array();
  18090. // Geometries
  18091. this._geometries = new Array();
  18092. this.materials = new Array();
  18093. this.multiMaterials = new Array();
  18094. // Textures
  18095. this._texturesEnabled = true;
  18096. this.textures = new Array();
  18097. // Particles
  18098. this.particlesEnabled = true;
  18099. this.particleSystems = new Array();
  18100. // Sprites
  18101. this.spritesEnabled = true;
  18102. this.spriteManagers = new Array();
  18103. // Layers
  18104. this.layers = new Array();
  18105. this.highlightLayers = new Array();
  18106. // Skeletons
  18107. this._skeletonsEnabled = true;
  18108. this.skeletons = new Array();
  18109. // Morph targets
  18110. this.morphTargetManagers = new Array();
  18111. // Lens flares
  18112. this.lensFlaresEnabled = true;
  18113. this.lensFlareSystems = new Array();
  18114. // Collisions
  18115. this.collisionsEnabled = true;
  18116. /** Defines the gravity applied to this scene */
  18117. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18118. // Postprocesses
  18119. this.postProcesses = new Array();
  18120. this.postProcessesEnabled = true;
  18121. // Customs render targets
  18122. this.renderTargetsEnabled = true;
  18123. this.dumpNextRenderTargets = false;
  18124. this.customRenderTargets = new Array();
  18125. // Imported meshes
  18126. this.importedMeshesFiles = new Array();
  18127. // Probes
  18128. this.probesEnabled = true;
  18129. this.reflectionProbes = new Array();
  18130. this._actionManagers = new Array();
  18131. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18132. // Procedural textures
  18133. this.proceduralTexturesEnabled = true;
  18134. this._proceduralTextures = new Array();
  18135. this.soundTracks = new Array();
  18136. this._audioEnabled = true;
  18137. this._headphone = false;
  18138. // Performance counters
  18139. this._totalVertices = new BABYLON.PerfCounter();
  18140. this._activeIndices = new BABYLON.PerfCounter();
  18141. this._activeParticles = new BABYLON.PerfCounter();
  18142. this._activeBones = new BABYLON.PerfCounter();
  18143. this._animationTime = 0;
  18144. this.animationTimeScale = 1;
  18145. this._renderId = 0;
  18146. this._executeWhenReadyTimeoutId = -1;
  18147. this._intermediateRendering = false;
  18148. this._viewUpdateFlag = -1;
  18149. this._projectionUpdateFlag = -1;
  18150. this._alternateViewUpdateFlag = -1;
  18151. this._alternateProjectionUpdateFlag = -1;
  18152. this._toBeDisposed = new BABYLON.SmartArray(256);
  18153. this._pendingData = new Array();
  18154. this._isDisposed = false;
  18155. this._activeMeshes = new BABYLON.SmartArray(256);
  18156. this._processedMaterials = new BABYLON.SmartArray(256);
  18157. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18158. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18159. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18160. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18161. this._activeAnimatables = new Array();
  18162. this._transformMatrix = BABYLON.Matrix.Zero();
  18163. this._useAlternateCameraConfiguration = false;
  18164. this._alternateRendering = false;
  18165. this.requireLightSorting = false;
  18166. this._activeMeshesFrozen = false;
  18167. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18168. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18169. this._engine.scenes.push(this);
  18170. this._uid = null;
  18171. this._renderingManager = new BABYLON.RenderingManager(this);
  18172. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18173. if (BABYLON.OutlineRenderer) {
  18174. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18175. }
  18176. if (BABYLON.Tools.IsWindowObjectExist()) {
  18177. this.attachControl();
  18178. }
  18179. //simplification queue
  18180. if (BABYLON.SimplificationQueue) {
  18181. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18182. }
  18183. //collision coordinator initialization. For now legacy per default.
  18184. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18185. // Uniform Buffer
  18186. this._createUbo();
  18187. // Default Image processing definition.
  18188. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18189. }
  18190. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18191. /** The fog is deactivated */
  18192. get: function () {
  18193. return Scene._FOGMODE_NONE;
  18194. },
  18195. enumerable: true,
  18196. configurable: true
  18197. });
  18198. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18199. /** The fog density is following an exponential function */
  18200. get: function () {
  18201. return Scene._FOGMODE_EXP;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18207. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18208. get: function () {
  18209. return Scene._FOGMODE_EXP2;
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18215. /** The fog density is following a linear function. */
  18216. get: function () {
  18217. return Scene._FOGMODE_LINEAR;
  18218. },
  18219. enumerable: true,
  18220. configurable: true
  18221. });
  18222. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18223. /**
  18224. * Texture used in all pbr material as the reflection texture.
  18225. * As in the majority of the scene they are the same (exception for multi room and so on),
  18226. * this is easier to reference from here than from all the materials.
  18227. */
  18228. get: function () {
  18229. return this._environmentTexture;
  18230. },
  18231. /**
  18232. * Texture used in all pbr material as the reflection texture.
  18233. * As in the majority of the scene they are the same (exception for multi room and so on),
  18234. * this is easier to set here than in all the materials.
  18235. */
  18236. set: function (value) {
  18237. if (this._environmentTexture === value) {
  18238. return;
  18239. }
  18240. this._environmentTexture = value;
  18241. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18247. /**
  18248. * Default image processing configuration used either in the rendering
  18249. * Forward main pass or through the imageProcessingPostProcess if present.
  18250. * As in the majority of the scene they are the same (exception for multi camera),
  18251. * this is easier to reference from here than from all the materials and post process.
  18252. *
  18253. * No setter as we it is a shared configuration, you can set the values instead.
  18254. */
  18255. get: function () {
  18256. return this._imageProcessingConfiguration;
  18257. },
  18258. enumerable: true,
  18259. configurable: true
  18260. });
  18261. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18262. get: function () {
  18263. return this._forcePointsCloud;
  18264. },
  18265. set: function (value) {
  18266. if (this._forcePointsCloud === value) {
  18267. return;
  18268. }
  18269. this._forcePointsCloud = value;
  18270. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18271. },
  18272. enumerable: true,
  18273. configurable: true
  18274. });
  18275. Object.defineProperty(Scene.prototype, "onDispose", {
  18276. /** A function to be executed when this scene is disposed. */
  18277. set: function (callback) {
  18278. if (this._onDisposeObserver) {
  18279. this.onDisposeObservable.remove(this._onDisposeObserver);
  18280. }
  18281. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. Object.defineProperty(Scene.prototype, "beforeRender", {
  18287. /** A function to be executed before rendering this scene */
  18288. set: function (callback) {
  18289. if (this._onBeforeRenderObserver) {
  18290. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18291. }
  18292. if (callback) {
  18293. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18294. }
  18295. },
  18296. enumerable: true,
  18297. configurable: true
  18298. });
  18299. Object.defineProperty(Scene.prototype, "afterRender", {
  18300. /** A function to be executed after rendering this scene */
  18301. set: function (callback) {
  18302. if (this._onAfterRenderObserver) {
  18303. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18304. }
  18305. if (callback) {
  18306. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18307. }
  18308. },
  18309. enumerable: true,
  18310. configurable: true
  18311. });
  18312. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18313. set: function (callback) {
  18314. if (this._onBeforeCameraRenderObserver) {
  18315. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18316. }
  18317. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18318. },
  18319. enumerable: true,
  18320. configurable: true
  18321. });
  18322. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18323. set: function (callback) {
  18324. if (this._onAfterCameraRenderObserver) {
  18325. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18326. }
  18327. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18328. },
  18329. enumerable: true,
  18330. configurable: true
  18331. });
  18332. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18333. get: function () {
  18334. if (!this._gamepadManager) {
  18335. this._gamepadManager = new BABYLON.GamepadManager(this);
  18336. }
  18337. return this._gamepadManager;
  18338. },
  18339. enumerable: true,
  18340. configurable: true
  18341. });
  18342. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18343. get: function () {
  18344. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18345. },
  18346. enumerable: true,
  18347. configurable: true
  18348. });
  18349. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18350. get: function () {
  18351. return this._useRightHandedSystem;
  18352. },
  18353. set: function (value) {
  18354. if (this._useRightHandedSystem === value) {
  18355. return;
  18356. }
  18357. this._useRightHandedSystem = value;
  18358. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18359. },
  18360. enumerable: true,
  18361. configurable: true
  18362. });
  18363. Scene.prototype.setStepId = function (newStepId) {
  18364. this._currentStepId = newStepId;
  18365. };
  18366. ;
  18367. Scene.prototype.getStepId = function () {
  18368. return this._currentStepId;
  18369. };
  18370. ;
  18371. Scene.prototype.getInternalStep = function () {
  18372. return this._currentInternalStep;
  18373. };
  18374. ;
  18375. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18376. get: function () {
  18377. return this._fogEnabled;
  18378. },
  18379. /**
  18380. * is fog enabled on this scene.
  18381. */
  18382. set: function (value) {
  18383. if (this._fogEnabled === value) {
  18384. return;
  18385. }
  18386. this._fogEnabled = value;
  18387. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(Scene.prototype, "fogMode", {
  18393. get: function () {
  18394. return this._fogMode;
  18395. },
  18396. set: function (value) {
  18397. if (this._fogMode === value) {
  18398. return;
  18399. }
  18400. this._fogMode = value;
  18401. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18402. },
  18403. enumerable: true,
  18404. configurable: true
  18405. });
  18406. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18407. get: function () {
  18408. return this._shadowsEnabled;
  18409. },
  18410. set: function (value) {
  18411. if (this._shadowsEnabled === value) {
  18412. return;
  18413. }
  18414. this._shadowsEnabled = value;
  18415. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18421. get: function () {
  18422. return this._lightsEnabled;
  18423. },
  18424. set: function (value) {
  18425. if (this._lightsEnabled === value) {
  18426. return;
  18427. }
  18428. this._lightsEnabled = value;
  18429. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18435. /** The default material used on meshes when no material is affected */
  18436. get: function () {
  18437. if (!this._defaultMaterial) {
  18438. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18439. }
  18440. return this._defaultMaterial;
  18441. },
  18442. /** The default material used on meshes when no material is affected */
  18443. set: function (value) {
  18444. this._defaultMaterial = value;
  18445. },
  18446. enumerable: true,
  18447. configurable: true
  18448. });
  18449. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18450. get: function () {
  18451. return this._texturesEnabled;
  18452. },
  18453. set: function (value) {
  18454. if (this._texturesEnabled === value) {
  18455. return;
  18456. }
  18457. this._texturesEnabled = value;
  18458. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18459. },
  18460. enumerable: true,
  18461. configurable: true
  18462. });
  18463. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18464. get: function () {
  18465. return this._skeletonsEnabled;
  18466. },
  18467. set: function (value) {
  18468. if (this._skeletonsEnabled === value) {
  18469. return;
  18470. }
  18471. this._skeletonsEnabled = value;
  18472. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18478. get: function () {
  18479. if (!this._postProcessRenderPipelineManager) {
  18480. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18481. }
  18482. return this._postProcessRenderPipelineManager;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18488. get: function () {
  18489. if (!this._mainSoundTrack) {
  18490. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18491. }
  18492. return this._mainSoundTrack;
  18493. },
  18494. enumerable: true,
  18495. configurable: true
  18496. });
  18497. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18498. get: function () {
  18499. return this._alternateRendering;
  18500. },
  18501. enumerable: true,
  18502. configurable: true
  18503. });
  18504. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18505. get: function () {
  18506. return this._frustumPlanes;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(Scene.prototype, "debugLayer", {
  18512. // Properties
  18513. get: function () {
  18514. if (!this._debugLayer) {
  18515. this._debugLayer = new BABYLON.DebugLayer(this);
  18516. }
  18517. return this._debugLayer;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18523. get: function () {
  18524. return this._workerCollisions;
  18525. },
  18526. set: function (enabled) {
  18527. if (!BABYLON.CollisionCoordinatorLegacy) {
  18528. return;
  18529. }
  18530. enabled = (enabled && !!Worker);
  18531. this._workerCollisions = enabled;
  18532. if (this.collisionCoordinator) {
  18533. this.collisionCoordinator.destroy();
  18534. }
  18535. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18536. this.collisionCoordinator.init(this);
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18542. get: function () {
  18543. return this._selectionOctree;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18549. /**
  18550. * The mesh that is currently under the pointer.
  18551. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18552. */
  18553. get: function () {
  18554. return this._pointerOverMesh;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. Object.defineProperty(Scene.prototype, "pointerX", {
  18560. /**
  18561. * Current on-screen X position of the pointer
  18562. * @return {number} X position of the pointer
  18563. */
  18564. get: function () {
  18565. return this._pointerX;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(Scene.prototype, "pointerY", {
  18571. /**
  18572. * Current on-screen Y position of the pointer
  18573. * @return {number} Y position of the pointer
  18574. */
  18575. get: function () {
  18576. return this._pointerY;
  18577. },
  18578. enumerable: true,
  18579. configurable: true
  18580. });
  18581. Scene.prototype.getCachedMaterial = function () {
  18582. return this._cachedMaterial;
  18583. };
  18584. Scene.prototype.getCachedEffect = function () {
  18585. return this._cachedEffect;
  18586. };
  18587. Scene.prototype.getCachedVisibility = function () {
  18588. return this._cachedVisibility;
  18589. };
  18590. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18591. if (visibility === void 0) { visibility = 1; }
  18592. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18593. };
  18594. Scene.prototype.getBoundingBoxRenderer = function () {
  18595. if (!this._boundingBoxRenderer) {
  18596. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18597. }
  18598. return this._boundingBoxRenderer;
  18599. };
  18600. Scene.prototype.getOutlineRenderer = function () {
  18601. return this._outlineRenderer;
  18602. };
  18603. Scene.prototype.getEngine = function () {
  18604. return this._engine;
  18605. };
  18606. Scene.prototype.getTotalVertices = function () {
  18607. return this._totalVertices.current;
  18608. };
  18609. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18610. get: function () {
  18611. return this._totalVertices;
  18612. },
  18613. enumerable: true,
  18614. configurable: true
  18615. });
  18616. Scene.prototype.getActiveIndices = function () {
  18617. return this._activeIndices.current;
  18618. };
  18619. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18620. get: function () {
  18621. return this._activeIndices;
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. Scene.prototype.getActiveParticles = function () {
  18627. return this._activeParticles.current;
  18628. };
  18629. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18630. get: function () {
  18631. return this._activeParticles;
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. Scene.prototype.getActiveBones = function () {
  18637. return this._activeBones.current;
  18638. };
  18639. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18640. get: function () {
  18641. return this._activeBones;
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. // Stats
  18647. Scene.prototype.getInterFramePerfCounter = function () {
  18648. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18649. return 0;
  18650. };
  18651. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18652. get: function () {
  18653. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18654. return null;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Scene.prototype.getLastFrameDuration = function () {
  18660. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18661. return 0;
  18662. };
  18663. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18664. get: function () {
  18665. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18666. return null;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18672. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18673. return 0;
  18674. };
  18675. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18676. get: function () {
  18677. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18678. return null;
  18679. },
  18680. enumerable: true,
  18681. configurable: true
  18682. });
  18683. Scene.prototype.getActiveMeshes = function () {
  18684. return this._activeMeshes;
  18685. };
  18686. Scene.prototype.getRenderTargetsDuration = function () {
  18687. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18688. return 0;
  18689. };
  18690. Scene.prototype.getRenderDuration = function () {
  18691. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18692. return 0;
  18693. };
  18694. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18695. get: function () {
  18696. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18697. return null;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. Scene.prototype.getParticlesDuration = function () {
  18703. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18704. return 0;
  18705. };
  18706. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18707. get: function () {
  18708. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18709. return null;
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Scene.prototype.getSpritesDuration = function () {
  18715. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18716. return 0;
  18717. };
  18718. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18719. get: function () {
  18720. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18721. return null;
  18722. },
  18723. enumerable: true,
  18724. configurable: true
  18725. });
  18726. Scene.prototype.getAnimationRatio = function () {
  18727. return this._animationRatio;
  18728. };
  18729. Scene.prototype.getRenderId = function () {
  18730. return this._renderId;
  18731. };
  18732. Scene.prototype.incrementRenderId = function () {
  18733. this._renderId++;
  18734. };
  18735. Scene.prototype._updatePointerPosition = function (evt) {
  18736. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18737. if (!canvasRect) {
  18738. return;
  18739. }
  18740. this._pointerX = evt.clientX - canvasRect.left;
  18741. this._pointerY = evt.clientY - canvasRect.top;
  18742. this._unTranslatedPointerX = this._pointerX;
  18743. this._unTranslatedPointerY = this._pointerY;
  18744. };
  18745. Scene.prototype._createUbo = function () {
  18746. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18747. this._sceneUbo.addUniform("viewProjection", 16);
  18748. this._sceneUbo.addUniform("view", 16);
  18749. };
  18750. Scene.prototype._createAlternateUbo = function () {
  18751. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18752. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18753. this._alternateSceneUbo.addUniform("view", 16);
  18754. };
  18755. // Pointers handling
  18756. /**
  18757. * Use this method to simulate a pointer move on a mesh
  18758. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18759. */
  18760. Scene.prototype.simulatePointerMove = function (pickResult) {
  18761. var evt = new PointerEvent("pointermove");
  18762. return this._processPointerMove(pickResult, evt);
  18763. };
  18764. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18765. var canvas = this._engine.getRenderingCanvas();
  18766. if (!canvas) {
  18767. return this;
  18768. }
  18769. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18770. this.setPointerOverSprite(null);
  18771. this.setPointerOverMesh(pickResult.pickedMesh);
  18772. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18773. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18774. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18775. }
  18776. else {
  18777. canvas.style.cursor = this.hoverCursor;
  18778. }
  18779. }
  18780. else {
  18781. canvas.style.cursor = this.defaultCursor;
  18782. }
  18783. }
  18784. else {
  18785. this.setPointerOverMesh(null);
  18786. // Sprites
  18787. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18788. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18789. this.setPointerOverSprite(pickResult.pickedSprite);
  18790. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18791. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18792. }
  18793. else {
  18794. canvas.style.cursor = this.hoverCursor;
  18795. }
  18796. }
  18797. else {
  18798. this.setPointerOverSprite(null);
  18799. // Restore pointer
  18800. canvas.style.cursor = this.defaultCursor;
  18801. }
  18802. }
  18803. if (pickResult) {
  18804. if (this.onPointerMove) {
  18805. this.onPointerMove(evt, pickResult);
  18806. }
  18807. if (this.onPointerObservable.hasObservers()) {
  18808. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18809. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18810. this.onPointerObservable.notifyObservers(pi, type);
  18811. }
  18812. }
  18813. return this;
  18814. };
  18815. /**
  18816. * Use this method to simulate a pointer down on a mesh
  18817. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18818. */
  18819. Scene.prototype.simulatePointerDown = function (pickResult) {
  18820. var evt = new PointerEvent("pointerdown");
  18821. return this._processPointerDown(pickResult, evt);
  18822. };
  18823. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18824. var _this = this;
  18825. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18826. this._pickedDownMesh = pickResult.pickedMesh;
  18827. var actionManager = pickResult.pickedMesh.actionManager;
  18828. if (actionManager) {
  18829. if (actionManager.hasPickTriggers) {
  18830. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18831. switch (evt.button) {
  18832. case 0:
  18833. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18834. break;
  18835. case 1:
  18836. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18837. break;
  18838. case 2:
  18839. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18840. break;
  18841. }
  18842. }
  18843. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18844. window.setTimeout(function () {
  18845. 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);
  18846. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18847. if (_this._totalPointersPressed !== 0 &&
  18848. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18849. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18850. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18851. _this._startingPointerTime = 0;
  18852. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18853. }
  18854. }
  18855. }, Scene.LongPressDelay);
  18856. }
  18857. }
  18858. }
  18859. if (pickResult) {
  18860. if (this.onPointerDown) {
  18861. this.onPointerDown(evt, pickResult);
  18862. }
  18863. if (this.onPointerObservable.hasObservers()) {
  18864. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18865. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18866. this.onPointerObservable.notifyObservers(pi, type);
  18867. }
  18868. }
  18869. return this;
  18870. };
  18871. /**
  18872. * Use this method to simulate a pointer up on a mesh
  18873. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18874. */
  18875. Scene.prototype.simulatePointerUp = function (pickResult) {
  18876. var evt = new PointerEvent("pointerup");
  18877. var clickInfo = new ClickInfo();
  18878. clickInfo.singleClick = true;
  18879. return this._processPointerUp(pickResult, evt, clickInfo);
  18880. };
  18881. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18882. if (pickResult && pickResult && pickResult.pickedMesh) {
  18883. this._pickedUpMesh = pickResult.pickedMesh;
  18884. if (this._pickedDownMesh === this._pickedUpMesh) {
  18885. if (this.onPointerPick) {
  18886. this.onPointerPick(evt, pickResult);
  18887. }
  18888. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18889. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18890. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18891. this.onPointerObservable.notifyObservers(pi, type);
  18892. }
  18893. }
  18894. if (pickResult.pickedMesh.actionManager) {
  18895. if (clickInfo.ignore) {
  18896. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18897. }
  18898. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18899. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18900. }
  18901. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18902. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18903. }
  18904. }
  18905. }
  18906. if (this._pickedDownMesh &&
  18907. this._pickedDownMesh.actionManager &&
  18908. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18909. this._pickedDownMesh !== this._pickedUpMesh) {
  18910. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18911. }
  18912. if (this.onPointerUp) {
  18913. this.onPointerUp(evt, pickResult);
  18914. }
  18915. if (this.onPointerObservable.hasObservers()) {
  18916. if (!clickInfo.ignore) {
  18917. if (!clickInfo.hasSwiped) {
  18918. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18919. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18920. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18921. this.onPointerObservable.notifyObservers(pi, type);
  18922. }
  18923. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18924. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18925. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18926. this.onPointerObservable.notifyObservers(pi, type);
  18927. }
  18928. }
  18929. }
  18930. else {
  18931. var type = BABYLON.PointerEventTypes.POINTERUP;
  18932. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18933. this.onPointerObservable.notifyObservers(pi, type);
  18934. }
  18935. }
  18936. return this;
  18937. };
  18938. /**
  18939. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18940. * @param attachUp defines if you want to attach events to pointerup
  18941. * @param attachDown defines if you want to attach events to pointerdown
  18942. * @param attachMove defines if you want to attach events to pointermove
  18943. */
  18944. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18945. var _this = this;
  18946. if (attachUp === void 0) { attachUp = true; }
  18947. if (attachDown === void 0) { attachDown = true; }
  18948. if (attachMove === void 0) { attachMove = true; }
  18949. this._initActionManager = function (act, clickInfo) {
  18950. if (!_this._meshPickProceed) {
  18951. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18952. _this._currentPickResult = pickResult;
  18953. if (pickResult) {
  18954. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18955. }
  18956. _this._meshPickProceed = true;
  18957. }
  18958. return act;
  18959. };
  18960. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18961. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18962. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18963. btn !== _this._previousButtonPressed) {
  18964. _this._doubleClickOccured = false;
  18965. clickInfo.singleClick = true;
  18966. clickInfo.ignore = false;
  18967. cb(clickInfo, _this._currentPickResult);
  18968. }
  18969. };
  18970. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18971. var clickInfo = new ClickInfo();
  18972. _this._currentPickResult = null;
  18973. var act = null;
  18974. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18975. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18976. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18977. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18978. act = _this._initActionManager(act, clickInfo);
  18979. if (act)
  18980. checkPicking = act.hasPickTriggers;
  18981. }
  18982. if (checkPicking) {
  18983. var btn = evt.button;
  18984. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18985. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18986. if (!clickInfo.hasSwiped) {
  18987. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18988. if (!checkSingleClickImmediately) {
  18989. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18990. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18991. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18992. act = _this._initActionManager(act, clickInfo);
  18993. if (act)
  18994. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18995. }
  18996. }
  18997. if (checkSingleClickImmediately) {
  18998. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18999. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19000. btn !== _this._previousButtonPressed) {
  19001. clickInfo.singleClick = true;
  19002. cb(clickInfo, _this._currentPickResult);
  19003. }
  19004. }
  19005. else {
  19006. // wait that no double click has been raised during the double click delay
  19007. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19008. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19009. }
  19010. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19011. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19012. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19013. act = _this._initActionManager(act, clickInfo);
  19014. if (act)
  19015. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19016. }
  19017. if (checkDoubleClick) {
  19018. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19019. if (btn === _this._previousButtonPressed &&
  19020. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19021. !_this._doubleClickOccured) {
  19022. // pointer has not moved for 2 clicks, it's a double click
  19023. if (!clickInfo.hasSwiped &&
  19024. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19025. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19026. _this._previousStartingPointerTime = 0;
  19027. _this._doubleClickOccured = true;
  19028. clickInfo.doubleClick = true;
  19029. clickInfo.ignore = false;
  19030. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19031. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19032. }
  19033. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19034. cb(clickInfo, _this._currentPickResult);
  19035. }
  19036. else {
  19037. _this._doubleClickOccured = false;
  19038. _this._previousStartingPointerTime = _this._startingPointerTime;
  19039. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19040. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19041. _this._previousButtonPressed = btn;
  19042. if (Scene.ExclusiveDoubleClickMode) {
  19043. if (_this._previousDelayedSimpleClickTimeout) {
  19044. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19045. }
  19046. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19047. cb(clickInfo, _this._previousPickResult);
  19048. }
  19049. else {
  19050. cb(clickInfo, _this._currentPickResult);
  19051. }
  19052. }
  19053. }
  19054. else {
  19055. _this._doubleClickOccured = false;
  19056. _this._previousStartingPointerTime = _this._startingPointerTime;
  19057. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19058. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19059. _this._previousButtonPressed = btn;
  19060. }
  19061. }
  19062. }
  19063. }
  19064. clickInfo.ignore = true;
  19065. cb(clickInfo, _this._currentPickResult);
  19066. };
  19067. this._spritePredicate = function (sprite) {
  19068. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19069. };
  19070. this._onPointerMove = function (evt) {
  19071. _this._updatePointerPosition(evt);
  19072. // PreObservable support
  19073. if (_this.onPrePointerObservable.hasObservers()) {
  19074. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19075. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19076. _this.onPrePointerObservable.notifyObservers(pi, type);
  19077. if (pi.skipOnPointerObservable) {
  19078. return;
  19079. }
  19080. }
  19081. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19082. return;
  19083. }
  19084. if (!_this.pointerMovePredicate) {
  19085. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19086. }
  19087. // Meshes
  19088. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19089. _this._processPointerMove(pickResult, evt);
  19090. };
  19091. this._onPointerDown = function (evt) {
  19092. _this._totalPointersPressed++;
  19093. _this._pickedDownMesh = null;
  19094. _this._meshPickProceed = false;
  19095. _this._updatePointerPosition(evt);
  19096. if (_this.preventDefaultOnPointerDown && canvas) {
  19097. evt.preventDefault();
  19098. canvas.focus();
  19099. }
  19100. // PreObservable support
  19101. if (_this.onPrePointerObservable.hasObservers()) {
  19102. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19103. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19104. _this.onPrePointerObservable.notifyObservers(pi, type);
  19105. if (pi.skipOnPointerObservable) {
  19106. return;
  19107. }
  19108. }
  19109. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19110. return;
  19111. }
  19112. _this._startingPointerPosition.x = _this._pointerX;
  19113. _this._startingPointerPosition.y = _this._pointerY;
  19114. _this._startingPointerTime = new Date().getTime();
  19115. if (!_this.pointerDownPredicate) {
  19116. _this.pointerDownPredicate = function (mesh) {
  19117. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19118. };
  19119. }
  19120. // Meshes
  19121. _this._pickedDownMesh = null;
  19122. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19123. _this._processPointerDown(pickResult, evt);
  19124. // Sprites
  19125. _this._pickedDownSprite = null;
  19126. if (_this.spriteManagers.length > 0) {
  19127. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19128. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19129. if (pickResult.pickedSprite.actionManager) {
  19130. _this._pickedDownSprite = pickResult.pickedSprite;
  19131. switch (evt.button) {
  19132. case 0:
  19133. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19134. break;
  19135. case 1:
  19136. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19137. break;
  19138. case 2:
  19139. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19140. break;
  19141. }
  19142. if (pickResult.pickedSprite.actionManager) {
  19143. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19144. }
  19145. }
  19146. }
  19147. }
  19148. };
  19149. this._onPointerUp = function (evt) {
  19150. if (_this._totalPointersPressed === 0) {
  19151. return; // So we need to test it the pointer down was pressed before.
  19152. }
  19153. _this._totalPointersPressed--;
  19154. _this._pickedUpMesh = null;
  19155. _this._meshPickProceed = false;
  19156. _this._updatePointerPosition(evt);
  19157. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19158. // PreObservable support
  19159. if (_this.onPrePointerObservable.hasObservers()) {
  19160. if (!clickInfo.ignore) {
  19161. if (!clickInfo.hasSwiped) {
  19162. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19163. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19164. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19165. _this.onPrePointerObservable.notifyObservers(pi, type);
  19166. if (pi.skipOnPointerObservable) {
  19167. return;
  19168. }
  19169. }
  19170. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19171. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19172. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19173. _this.onPrePointerObservable.notifyObservers(pi, type);
  19174. if (pi.skipOnPointerObservable) {
  19175. return;
  19176. }
  19177. }
  19178. }
  19179. }
  19180. else {
  19181. var type = BABYLON.PointerEventTypes.POINTERUP;
  19182. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19183. _this.onPrePointerObservable.notifyObservers(pi, type);
  19184. if (pi.skipOnPointerObservable) {
  19185. return;
  19186. }
  19187. }
  19188. }
  19189. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19190. return;
  19191. }
  19192. if (!_this.pointerUpPredicate) {
  19193. _this.pointerUpPredicate = function (mesh) {
  19194. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19195. };
  19196. }
  19197. // Meshes
  19198. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19199. _this._initActionManager(null, clickInfo);
  19200. }
  19201. if (!pickResult) {
  19202. pickResult = _this._currentPickResult;
  19203. }
  19204. _this._processPointerUp(pickResult, evt, clickInfo);
  19205. // Sprites
  19206. if (_this.spriteManagers.length > 0) {
  19207. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19208. if (spritePickResult) {
  19209. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19210. if (spritePickResult.pickedSprite.actionManager) {
  19211. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19212. if (spritePickResult.pickedSprite.actionManager) {
  19213. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19214. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19215. }
  19216. }
  19217. }
  19218. }
  19219. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19220. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19221. }
  19222. }
  19223. }
  19224. _this._previousPickResult = _this._currentPickResult;
  19225. });
  19226. };
  19227. this._onKeyDown = function (evt) {
  19228. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19229. if (_this.onPreKeyboardObservable.hasObservers()) {
  19230. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19231. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19232. if (pi.skipOnPointerObservable) {
  19233. return;
  19234. }
  19235. }
  19236. if (_this.onKeyboardObservable.hasObservers()) {
  19237. var pi = new BABYLON.KeyboardInfo(type, evt);
  19238. _this.onKeyboardObservable.notifyObservers(pi, type);
  19239. }
  19240. if (_this.actionManager) {
  19241. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19242. }
  19243. };
  19244. this._onKeyUp = function (evt) {
  19245. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19246. if (_this.onPreKeyboardObservable.hasObservers()) {
  19247. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19248. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19249. if (pi.skipOnPointerObservable) {
  19250. return;
  19251. }
  19252. }
  19253. if (_this.onKeyboardObservable.hasObservers()) {
  19254. var pi = new BABYLON.KeyboardInfo(type, evt);
  19255. _this.onKeyboardObservable.notifyObservers(pi, type);
  19256. }
  19257. if (_this.actionManager) {
  19258. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19259. }
  19260. };
  19261. var engine = this.getEngine();
  19262. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19263. if (!canvas) {
  19264. return;
  19265. }
  19266. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19267. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19268. });
  19269. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19270. if (!canvas) {
  19271. return;
  19272. }
  19273. canvas.removeEventListener("keydown", _this._onKeyDown);
  19274. canvas.removeEventListener("keyup", _this._onKeyUp);
  19275. });
  19276. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19277. var canvas = this._engine.getRenderingCanvas();
  19278. if (!canvas) {
  19279. return;
  19280. }
  19281. if (attachMove) {
  19282. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19283. // Wheel
  19284. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19285. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19286. }
  19287. if (attachDown) {
  19288. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19289. }
  19290. if (attachUp) {
  19291. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19292. }
  19293. canvas.tabIndex = 1;
  19294. };
  19295. Scene.prototype.detachControl = function () {
  19296. var engine = this.getEngine();
  19297. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19298. var canvas = engine.getRenderingCanvas();
  19299. if (!canvas) {
  19300. return;
  19301. }
  19302. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19303. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19304. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19305. if (this._onCanvasBlurObserver) {
  19306. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19307. }
  19308. if (this._onCanvasFocusObserver) {
  19309. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19310. }
  19311. // Wheel
  19312. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19313. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19314. // Keyboard
  19315. canvas.removeEventListener("keydown", this._onKeyDown);
  19316. canvas.removeEventListener("keyup", this._onKeyUp);
  19317. // Observables
  19318. this.onKeyboardObservable.clear();
  19319. this.onPreKeyboardObservable.clear();
  19320. this.onPointerObservable.clear();
  19321. this.onPrePointerObservable.clear();
  19322. };
  19323. // Ready
  19324. Scene.prototype.isReady = function () {
  19325. if (this._isDisposed) {
  19326. return false;
  19327. }
  19328. if (this._pendingData.length > 0) {
  19329. return false;
  19330. }
  19331. var index;
  19332. // Geometries
  19333. for (index = 0; index < this._geometries.length; index++) {
  19334. var geometry = this._geometries[index];
  19335. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19336. return false;
  19337. }
  19338. }
  19339. // Meshes
  19340. for (index = 0; index < this.meshes.length; index++) {
  19341. var mesh = this.meshes[index];
  19342. if (!mesh.isEnabled()) {
  19343. continue;
  19344. }
  19345. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19346. continue;
  19347. }
  19348. if (!mesh.isReady()) {
  19349. return false;
  19350. }
  19351. var mat = mesh.material;
  19352. if (mat) {
  19353. if (!mat.isReady(mesh)) {
  19354. return false;
  19355. }
  19356. }
  19357. }
  19358. return true;
  19359. };
  19360. Scene.prototype.resetCachedMaterial = function () {
  19361. this._cachedMaterial = null;
  19362. this._cachedEffect = null;
  19363. this._cachedVisibility = null;
  19364. };
  19365. Scene.prototype.registerBeforeRender = function (func) {
  19366. this.onBeforeRenderObservable.add(func);
  19367. };
  19368. Scene.prototype.unregisterBeforeRender = function (func) {
  19369. this.onBeforeRenderObservable.removeCallback(func);
  19370. };
  19371. Scene.prototype.registerAfterRender = function (func) {
  19372. this.onAfterRenderObservable.add(func);
  19373. };
  19374. Scene.prototype.unregisterAfterRender = function (func) {
  19375. this.onAfterRenderObservable.removeCallback(func);
  19376. };
  19377. Scene.prototype._addPendingData = function (data) {
  19378. this._pendingData.push(data);
  19379. };
  19380. Scene.prototype._removePendingData = function (data) {
  19381. var wasLoading = this.isLoading;
  19382. var index = this._pendingData.indexOf(data);
  19383. if (index !== -1) {
  19384. this._pendingData.splice(index, 1);
  19385. }
  19386. if (wasLoading && !this.isLoading) {
  19387. this.onDataLoadedObservable.notifyObservers(this);
  19388. }
  19389. };
  19390. Scene.prototype.getWaitingItemsCount = function () {
  19391. return this._pendingData.length;
  19392. };
  19393. Object.defineProperty(Scene.prototype, "isLoading", {
  19394. get: function () {
  19395. return this._pendingData.length > 0;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. /**
  19401. * Registers a function to be executed when the scene is ready.
  19402. * @param {Function} func - the function to be executed.
  19403. */
  19404. Scene.prototype.executeWhenReady = function (func) {
  19405. var _this = this;
  19406. this.onReadyObservable.add(func);
  19407. if (this._executeWhenReadyTimeoutId !== -1) {
  19408. return;
  19409. }
  19410. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19411. _this._checkIsReady();
  19412. }, 150);
  19413. };
  19414. Scene.prototype._checkIsReady = function () {
  19415. var _this = this;
  19416. if (this.isReady()) {
  19417. this.onReadyObservable.notifyObservers(this);
  19418. this.onReadyObservable.clear();
  19419. this._executeWhenReadyTimeoutId = -1;
  19420. return;
  19421. }
  19422. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19423. _this._checkIsReady();
  19424. }, 150);
  19425. };
  19426. // Animations
  19427. /**
  19428. * Will start the animation sequence of a given target
  19429. * @param target - the target
  19430. * @param {number} from - from which frame should animation start
  19431. * @param {number} to - till which frame should animation run.
  19432. * @param {boolean} [loop] - should the animation loop
  19433. * @param {number} [speedRatio] - the speed in which to run the animation
  19434. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19435. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19436. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19437. * See BABYLON.Animatable
  19438. */
  19439. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19440. if (speedRatio === void 0) { speedRatio = 1.0; }
  19441. if (from > to && speedRatio > 0) {
  19442. speedRatio *= -1;
  19443. }
  19444. this.stopAnimation(target);
  19445. if (!animatable) {
  19446. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19447. }
  19448. // Local animations
  19449. if (target.animations) {
  19450. animatable.appendAnimations(target, target.animations);
  19451. }
  19452. // Children animations
  19453. if (target.getAnimatables) {
  19454. var animatables = target.getAnimatables();
  19455. for (var index = 0; index < animatables.length; index++) {
  19456. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19457. }
  19458. }
  19459. animatable.reset();
  19460. return animatable;
  19461. };
  19462. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19463. if (speedRatio === undefined) {
  19464. speedRatio = 1.0;
  19465. }
  19466. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19467. return animatable;
  19468. };
  19469. Scene.prototype.getAnimatableByTarget = function (target) {
  19470. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19471. if (this._activeAnimatables[index].target === target) {
  19472. return this._activeAnimatables[index];
  19473. }
  19474. }
  19475. return null;
  19476. };
  19477. Object.defineProperty(Scene.prototype, "Animatables", {
  19478. get: function () {
  19479. return this._activeAnimatables;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. /**
  19485. * Will stop the animation of the given target
  19486. * @param target - the target
  19487. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19488. * @see beginAnimation
  19489. */
  19490. Scene.prototype.stopAnimation = function (target, animationName) {
  19491. var animatable = this.getAnimatableByTarget(target);
  19492. if (animatable) {
  19493. animatable.stop(animationName);
  19494. }
  19495. };
  19496. /**
  19497. * Stops and removes all animations that have been applied to the scene
  19498. */
  19499. Scene.prototype.stopAllAnimations = function () {
  19500. if (this._activeAnimatables) {
  19501. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19502. this._activeAnimatables[i].stop();
  19503. }
  19504. this._activeAnimatables = [];
  19505. }
  19506. };
  19507. Scene.prototype._animate = function () {
  19508. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19509. return;
  19510. }
  19511. // Getting time
  19512. var now = BABYLON.Tools.Now;
  19513. if (!this._animationTimeLast) {
  19514. if (this._pendingData.length > 0) {
  19515. return;
  19516. }
  19517. this._animationTimeLast = now;
  19518. }
  19519. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19520. this._animationTime += deltaTime;
  19521. this._animationTimeLast = now;
  19522. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19523. this._activeAnimatables[index]._animate(this._animationTime);
  19524. }
  19525. };
  19526. // Matrix
  19527. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19528. this._useAlternateCameraConfiguration = active;
  19529. };
  19530. Scene.prototype.getViewMatrix = function () {
  19531. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19532. };
  19533. Scene.prototype.getProjectionMatrix = function () {
  19534. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19535. };
  19536. Scene.prototype.getTransformMatrix = function () {
  19537. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19538. };
  19539. Scene.prototype.setTransformMatrix = function (view, projection) {
  19540. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19541. return;
  19542. }
  19543. this._viewUpdateFlag = view.updateFlag;
  19544. this._projectionUpdateFlag = projection.updateFlag;
  19545. this._viewMatrix = view;
  19546. this._projectionMatrix = projection;
  19547. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19548. // Update frustum
  19549. if (!this._frustumPlanes) {
  19550. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19551. }
  19552. else {
  19553. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19554. }
  19555. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19556. var otherCamera = this.activeCamera._alternateCamera;
  19557. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19558. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19559. }
  19560. if (this._sceneUbo.useUbo) {
  19561. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19562. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19563. this._sceneUbo.update();
  19564. }
  19565. };
  19566. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19567. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19568. return;
  19569. }
  19570. this._alternateViewUpdateFlag = view.updateFlag;
  19571. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19572. this._alternateViewMatrix = view;
  19573. this._alternateProjectionMatrix = projection;
  19574. if (!this._alternateTransformMatrix) {
  19575. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19576. }
  19577. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19578. if (!this._alternateSceneUbo) {
  19579. this._createAlternateUbo();
  19580. }
  19581. if (this._alternateSceneUbo.useUbo) {
  19582. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19583. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19584. this._alternateSceneUbo.update();
  19585. }
  19586. };
  19587. Scene.prototype.getSceneUniformBuffer = function () {
  19588. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19589. };
  19590. // Methods
  19591. Scene.prototype.getUniqueId = function () {
  19592. var result = Scene._uniqueIdCounter;
  19593. Scene._uniqueIdCounter++;
  19594. return result;
  19595. };
  19596. Scene.prototype.addMesh = function (newMesh) {
  19597. this.meshes.push(newMesh);
  19598. //notify the collision coordinator
  19599. if (this.collisionCoordinator) {
  19600. this.collisionCoordinator.onMeshAdded(newMesh);
  19601. }
  19602. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19603. };
  19604. Scene.prototype.removeMesh = function (toRemove) {
  19605. var index = this.meshes.indexOf(toRemove);
  19606. if (index !== -1) {
  19607. // Remove from the scene if mesh found
  19608. this.meshes.splice(index, 1);
  19609. }
  19610. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19611. return index;
  19612. };
  19613. Scene.prototype.addTransformNode = function (newTransformNode) {
  19614. this.transformNodes.push(newTransformNode);
  19615. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19616. };
  19617. Scene.prototype.removeTransformNode = function (toRemove) {
  19618. var index = this.transformNodes.indexOf(toRemove);
  19619. if (index !== -1) {
  19620. // Remove from the scene if found
  19621. this.transformNodes.splice(index, 1);
  19622. }
  19623. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19624. return index;
  19625. };
  19626. Scene.prototype.removeSkeleton = function (toRemove) {
  19627. var index = this.skeletons.indexOf(toRemove);
  19628. if (index !== -1) {
  19629. // Remove from the scene if found
  19630. this.skeletons.splice(index, 1);
  19631. }
  19632. return index;
  19633. };
  19634. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19635. var index = this.morphTargetManagers.indexOf(toRemove);
  19636. if (index !== -1) {
  19637. // Remove from the scene if found
  19638. this.morphTargetManagers.splice(index, 1);
  19639. }
  19640. return index;
  19641. };
  19642. Scene.prototype.removeLight = function (toRemove) {
  19643. var index = this.lights.indexOf(toRemove);
  19644. if (index !== -1) {
  19645. // Remove from the scene if mesh found
  19646. this.lights.splice(index, 1);
  19647. this.sortLightsByPriority();
  19648. }
  19649. this.onLightRemovedObservable.notifyObservers(toRemove);
  19650. return index;
  19651. };
  19652. Scene.prototype.removeCamera = function (toRemove) {
  19653. var index = this.cameras.indexOf(toRemove);
  19654. if (index !== -1) {
  19655. // Remove from the scene if mesh found
  19656. this.cameras.splice(index, 1);
  19657. }
  19658. // Remove from activeCameras
  19659. var index2 = this.activeCameras.indexOf(toRemove);
  19660. if (index2 !== -1) {
  19661. // Remove from the scene if mesh found
  19662. this.activeCameras.splice(index2, 1);
  19663. }
  19664. // Reset the activeCamera
  19665. if (this.activeCamera === toRemove) {
  19666. if (this.cameras.length > 0) {
  19667. this.activeCamera = this.cameras[0];
  19668. }
  19669. else {
  19670. this.activeCamera = null;
  19671. }
  19672. }
  19673. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19674. return index;
  19675. };
  19676. Scene.prototype.addLight = function (newLight) {
  19677. this.lights.push(newLight);
  19678. this.sortLightsByPriority();
  19679. this.onNewLightAddedObservable.notifyObservers(newLight);
  19680. };
  19681. Scene.prototype.sortLightsByPriority = function () {
  19682. if (this.requireLightSorting) {
  19683. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19684. }
  19685. };
  19686. Scene.prototype.addCamera = function (newCamera) {
  19687. this.cameras.push(newCamera);
  19688. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19689. };
  19690. /**
  19691. * Switch active camera
  19692. * @param {Camera} newCamera - new active camera
  19693. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19694. */
  19695. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19696. if (attachControl === void 0) { attachControl = true; }
  19697. var canvas = this._engine.getRenderingCanvas();
  19698. if (!canvas) {
  19699. return;
  19700. }
  19701. if (this.activeCamera) {
  19702. this.activeCamera.detachControl(canvas);
  19703. }
  19704. this.activeCamera = newCamera;
  19705. if (attachControl) {
  19706. newCamera.attachControl(canvas);
  19707. }
  19708. };
  19709. /**
  19710. * sets the active camera of the scene using its ID
  19711. * @param {string} id - the camera's ID
  19712. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19713. * @see activeCamera
  19714. */
  19715. Scene.prototype.setActiveCameraByID = function (id) {
  19716. var camera = this.getCameraByID(id);
  19717. if (camera) {
  19718. this.activeCamera = camera;
  19719. return camera;
  19720. }
  19721. return null;
  19722. };
  19723. /**
  19724. * sets the active camera of the scene using its name
  19725. * @param {string} name - the camera's name
  19726. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19727. * @see activeCamera
  19728. */
  19729. Scene.prototype.setActiveCameraByName = function (name) {
  19730. var camera = this.getCameraByName(name);
  19731. if (camera) {
  19732. this.activeCamera = camera;
  19733. return camera;
  19734. }
  19735. return null;
  19736. };
  19737. /**
  19738. * get a material using its id
  19739. * @param {string} the material's ID
  19740. * @return {BABYLON.Material|null} the material or null if none found.
  19741. */
  19742. Scene.prototype.getMaterialByID = function (id) {
  19743. for (var index = 0; index < this.materials.length; index++) {
  19744. if (this.materials[index].id === id) {
  19745. return this.materials[index];
  19746. }
  19747. }
  19748. return null;
  19749. };
  19750. /**
  19751. * get a material using its name
  19752. * @param {string} the material's name
  19753. * @return {BABYLON.Material|null} the material or null if none found.
  19754. */
  19755. Scene.prototype.getMaterialByName = function (name) {
  19756. for (var index = 0; index < this.materials.length; index++) {
  19757. if (this.materials[index].name === name) {
  19758. return this.materials[index];
  19759. }
  19760. }
  19761. return null;
  19762. };
  19763. Scene.prototype.getLensFlareSystemByName = function (name) {
  19764. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19765. if (this.lensFlareSystems[index].name === name) {
  19766. return this.lensFlareSystems[index];
  19767. }
  19768. }
  19769. return null;
  19770. };
  19771. Scene.prototype.getLensFlareSystemByID = function (id) {
  19772. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19773. if (this.lensFlareSystems[index].id === id) {
  19774. return this.lensFlareSystems[index];
  19775. }
  19776. }
  19777. return null;
  19778. };
  19779. Scene.prototype.getCameraByID = function (id) {
  19780. for (var index = 0; index < this.cameras.length; index++) {
  19781. if (this.cameras[index].id === id) {
  19782. return this.cameras[index];
  19783. }
  19784. }
  19785. return null;
  19786. };
  19787. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19788. for (var index = 0; index < this.cameras.length; index++) {
  19789. if (this.cameras[index].uniqueId === uniqueId) {
  19790. return this.cameras[index];
  19791. }
  19792. }
  19793. return null;
  19794. };
  19795. /**
  19796. * get a camera using its name
  19797. * @param {string} the camera's name
  19798. * @return {BABYLON.Camera|null} the camera or null if none found.
  19799. */
  19800. Scene.prototype.getCameraByName = function (name) {
  19801. for (var index = 0; index < this.cameras.length; index++) {
  19802. if (this.cameras[index].name === name) {
  19803. return this.cameras[index];
  19804. }
  19805. }
  19806. return null;
  19807. };
  19808. /**
  19809. * get a bone using its id
  19810. * @param {string} the bone's id
  19811. * @return {BABYLON.Bone|null} the bone or null if not found
  19812. */
  19813. Scene.prototype.getBoneByID = function (id) {
  19814. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19815. var skeleton = this.skeletons[skeletonIndex];
  19816. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19817. if (skeleton.bones[boneIndex].id === id) {
  19818. return skeleton.bones[boneIndex];
  19819. }
  19820. }
  19821. }
  19822. return null;
  19823. };
  19824. /**
  19825. * get a bone using its id
  19826. * @param {string} the bone's name
  19827. * @return {BABYLON.Bone|null} the bone or null if not found
  19828. */
  19829. Scene.prototype.getBoneByName = function (name) {
  19830. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19831. var skeleton = this.skeletons[skeletonIndex];
  19832. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19833. if (skeleton.bones[boneIndex].name === name) {
  19834. return skeleton.bones[boneIndex];
  19835. }
  19836. }
  19837. }
  19838. return null;
  19839. };
  19840. /**
  19841. * get a light node using its name
  19842. * @param {string} the light's name
  19843. * @return {BABYLON.Light|null} the light or null if none found.
  19844. */
  19845. Scene.prototype.getLightByName = function (name) {
  19846. for (var index = 0; index < this.lights.length; index++) {
  19847. if (this.lights[index].name === name) {
  19848. return this.lights[index];
  19849. }
  19850. }
  19851. return null;
  19852. };
  19853. /**
  19854. * get a light node using its ID
  19855. * @param {string} the light's id
  19856. * @return {BABYLON.Light|null} the light or null if none found.
  19857. */
  19858. Scene.prototype.getLightByID = function (id) {
  19859. for (var index = 0; index < this.lights.length; index++) {
  19860. if (this.lights[index].id === id) {
  19861. return this.lights[index];
  19862. }
  19863. }
  19864. return null;
  19865. };
  19866. /**
  19867. * get a light node using its scene-generated unique ID
  19868. * @param {number} the light's unique id
  19869. * @return {BABYLON.Light|null} the light or null if none found.
  19870. */
  19871. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19872. for (var index = 0; index < this.lights.length; index++) {
  19873. if (this.lights[index].uniqueId === uniqueId) {
  19874. return this.lights[index];
  19875. }
  19876. }
  19877. return null;
  19878. };
  19879. /**
  19880. * get a particle system by id
  19881. * @param id {number} the particle system id
  19882. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19883. */
  19884. Scene.prototype.getParticleSystemByID = function (id) {
  19885. for (var index = 0; index < this.particleSystems.length; index++) {
  19886. if (this.particleSystems[index].id === id) {
  19887. return this.particleSystems[index];
  19888. }
  19889. }
  19890. return null;
  19891. };
  19892. /**
  19893. * get a geometry using its ID
  19894. * @param {string} the geometry's id
  19895. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19896. */
  19897. Scene.prototype.getGeometryByID = function (id) {
  19898. for (var index = 0; index < this._geometries.length; index++) {
  19899. if (this._geometries[index].id === id) {
  19900. return this._geometries[index];
  19901. }
  19902. }
  19903. return null;
  19904. };
  19905. /**
  19906. * add a new geometry to this scene.
  19907. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19908. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19909. * @return {boolean} was the geometry added or not
  19910. */
  19911. Scene.prototype.pushGeometry = function (geometry, force) {
  19912. if (!force && this.getGeometryByID(geometry.id)) {
  19913. return false;
  19914. }
  19915. this._geometries.push(geometry);
  19916. //notify the collision coordinator
  19917. if (this.collisionCoordinator) {
  19918. this.collisionCoordinator.onGeometryAdded(geometry);
  19919. }
  19920. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19921. return true;
  19922. };
  19923. /**
  19924. * Removes an existing geometry
  19925. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19926. * @return {boolean} was the geometry removed or not
  19927. */
  19928. Scene.prototype.removeGeometry = function (geometry) {
  19929. var index = this._geometries.indexOf(geometry);
  19930. if (index > -1) {
  19931. this._geometries.splice(index, 1);
  19932. //notify the collision coordinator
  19933. if (this.collisionCoordinator) {
  19934. this.collisionCoordinator.onGeometryDeleted(geometry);
  19935. }
  19936. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19937. return true;
  19938. }
  19939. return false;
  19940. };
  19941. Scene.prototype.getGeometries = function () {
  19942. return this._geometries;
  19943. };
  19944. /**
  19945. * Get the first added mesh found of a given ID
  19946. * @param {string} id - the id to search for
  19947. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19948. */
  19949. Scene.prototype.getMeshByID = function (id) {
  19950. for (var index = 0; index < this.meshes.length; index++) {
  19951. if (this.meshes[index].id === id) {
  19952. return this.meshes[index];
  19953. }
  19954. }
  19955. return null;
  19956. };
  19957. Scene.prototype.getMeshesByID = function (id) {
  19958. return this.meshes.filter(function (m) {
  19959. return m.id === id;
  19960. });
  19961. };
  19962. /**
  19963. * Get the first added transform node found of a given ID
  19964. * @param {string} id - the id to search for
  19965. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  19966. */
  19967. Scene.prototype.getTransformNodeByID = function (id) {
  19968. for (var index = 0; index < this.transformNodes.length; index++) {
  19969. if (this.transformNodes[index].id === id) {
  19970. return this.transformNodes[index];
  19971. }
  19972. }
  19973. return null;
  19974. };
  19975. Scene.prototype.getTransformNodesByID = function (id) {
  19976. return this.transformNodes.filter(function (m) {
  19977. return m.id === id;
  19978. });
  19979. };
  19980. /**
  19981. * Get a mesh with its auto-generated unique id
  19982. * @param {number} uniqueId - the unique id to search for
  19983. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19984. */
  19985. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19986. for (var index = 0; index < this.meshes.length; index++) {
  19987. if (this.meshes[index].uniqueId === uniqueId) {
  19988. return this.meshes[index];
  19989. }
  19990. }
  19991. return null;
  19992. };
  19993. /**
  19994. * Get a the last added mesh found of a given ID
  19995. * @param {string} id - the id to search for
  19996. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19997. */
  19998. Scene.prototype.getLastMeshByID = function (id) {
  19999. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20000. if (this.meshes[index].id === id) {
  20001. return this.meshes[index];
  20002. }
  20003. }
  20004. return null;
  20005. };
  20006. /**
  20007. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20008. * @param {string} id - the id to search for
  20009. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20010. */
  20011. Scene.prototype.getLastEntryByID = function (id) {
  20012. var index;
  20013. for (index = this.meshes.length - 1; index >= 0; index--) {
  20014. if (this.meshes[index].id === id) {
  20015. return this.meshes[index];
  20016. }
  20017. }
  20018. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20019. if (this.transformNodes[index].id === id) {
  20020. return this.transformNodes[index];
  20021. }
  20022. }
  20023. for (index = this.cameras.length - 1; index >= 0; index--) {
  20024. if (this.cameras[index].id === id) {
  20025. return this.cameras[index];
  20026. }
  20027. }
  20028. for (index = this.lights.length - 1; index >= 0; index--) {
  20029. if (this.lights[index].id === id) {
  20030. return this.lights[index];
  20031. }
  20032. }
  20033. return null;
  20034. };
  20035. Scene.prototype.getNodeByID = function (id) {
  20036. var mesh = this.getMeshByID(id);
  20037. if (mesh) {
  20038. return mesh;
  20039. }
  20040. var light = this.getLightByID(id);
  20041. if (light) {
  20042. return light;
  20043. }
  20044. var camera = this.getCameraByID(id);
  20045. if (camera) {
  20046. return camera;
  20047. }
  20048. var bone = this.getBoneByID(id);
  20049. return bone;
  20050. };
  20051. Scene.prototype.getNodeByName = function (name) {
  20052. var mesh = this.getMeshByName(name);
  20053. if (mesh) {
  20054. return mesh;
  20055. }
  20056. var light = this.getLightByName(name);
  20057. if (light) {
  20058. return light;
  20059. }
  20060. var camera = this.getCameraByName(name);
  20061. if (camera) {
  20062. return camera;
  20063. }
  20064. var bone = this.getBoneByName(name);
  20065. return bone;
  20066. };
  20067. Scene.prototype.getMeshByName = function (name) {
  20068. for (var index = 0; index < this.meshes.length; index++) {
  20069. if (this.meshes[index].name === name) {
  20070. return this.meshes[index];
  20071. }
  20072. }
  20073. return null;
  20074. };
  20075. Scene.prototype.getTransformNodeByName = function (name) {
  20076. for (var index = 0; index < this.transformNodes.length; index++) {
  20077. if (this.transformNodes[index].name === name) {
  20078. return this.transformNodes[index];
  20079. }
  20080. }
  20081. return null;
  20082. };
  20083. Scene.prototype.getSoundByName = function (name) {
  20084. var index;
  20085. if (BABYLON.AudioEngine) {
  20086. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20087. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20088. return this.mainSoundTrack.soundCollection[index];
  20089. }
  20090. }
  20091. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20092. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20093. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20094. return this.soundTracks[sdIndex].soundCollection[index];
  20095. }
  20096. }
  20097. }
  20098. }
  20099. return null;
  20100. };
  20101. Scene.prototype.getLastSkeletonByID = function (id) {
  20102. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20103. if (this.skeletons[index].id === id) {
  20104. return this.skeletons[index];
  20105. }
  20106. }
  20107. return null;
  20108. };
  20109. Scene.prototype.getSkeletonById = function (id) {
  20110. for (var index = 0; index < this.skeletons.length; index++) {
  20111. if (this.skeletons[index].id === id) {
  20112. return this.skeletons[index];
  20113. }
  20114. }
  20115. return null;
  20116. };
  20117. Scene.prototype.getSkeletonByName = function (name) {
  20118. for (var index = 0; index < this.skeletons.length; index++) {
  20119. if (this.skeletons[index].name === name) {
  20120. return this.skeletons[index];
  20121. }
  20122. }
  20123. return null;
  20124. };
  20125. Scene.prototype.getMorphTargetManagerById = function (id) {
  20126. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20127. if (this.morphTargetManagers[index].uniqueId === id) {
  20128. return this.morphTargetManagers[index];
  20129. }
  20130. }
  20131. return null;
  20132. };
  20133. Scene.prototype.isActiveMesh = function (mesh) {
  20134. return (this._activeMeshes.indexOf(mesh) !== -1);
  20135. };
  20136. /**
  20137. * Return a the first highlight layer of the scene with a given name.
  20138. * @param name The name of the highlight layer to look for.
  20139. * @return The highlight layer if found otherwise null.
  20140. */
  20141. Scene.prototype.getHighlightLayerByName = function (name) {
  20142. for (var index = 0; index < this.highlightLayers.length; index++) {
  20143. if (this.highlightLayers[index].name === name) {
  20144. return this.highlightLayers[index];
  20145. }
  20146. }
  20147. return null;
  20148. };
  20149. Object.defineProperty(Scene.prototype, "uid", {
  20150. /**
  20151. * Return a unique id as a string which can serve as an identifier for the scene
  20152. */
  20153. get: function () {
  20154. if (!this._uid) {
  20155. this._uid = BABYLON.Tools.RandomId();
  20156. }
  20157. return this._uid;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. /**
  20163. * Add an externaly attached data from its key.
  20164. * This method call will fail and return false, if such key already exists.
  20165. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20166. * @param key the unique key that identifies the data
  20167. * @param data the data object to associate to the key for this Engine instance
  20168. * @return true if no such key were already present and the data was added successfully, false otherwise
  20169. */
  20170. Scene.prototype.addExternalData = function (key, data) {
  20171. if (!this._externalData) {
  20172. this._externalData = new BABYLON.StringDictionary();
  20173. }
  20174. return this._externalData.add(key, data);
  20175. };
  20176. /**
  20177. * Get an externaly attached data from its key
  20178. * @param key the unique key that identifies the data
  20179. * @return the associated data, if present (can be null), or undefined if not present
  20180. */
  20181. Scene.prototype.getExternalData = function (key) {
  20182. if (!this._externalData) {
  20183. return null;
  20184. }
  20185. return this._externalData.get(key);
  20186. };
  20187. /**
  20188. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20189. * @param key the unique key that identifies the data
  20190. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20191. * @return the associated data, can be null if the factory returned null.
  20192. */
  20193. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20194. if (!this._externalData) {
  20195. this._externalData = new BABYLON.StringDictionary();
  20196. }
  20197. return this._externalData.getOrAddWithFactory(key, factory);
  20198. };
  20199. /**
  20200. * Remove an externaly attached data from the Engine instance
  20201. * @param key the unique key that identifies the data
  20202. * @return true if the data was successfully removed, false if it doesn't exist
  20203. */
  20204. Scene.prototype.removeExternalData = function (key) {
  20205. return this._externalData.remove(key);
  20206. };
  20207. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20208. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20209. var material = subMesh.getMaterial();
  20210. if (mesh.showSubMeshesBoundingBox) {
  20211. var boundingInfo = subMesh.getBoundingInfo();
  20212. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20213. }
  20214. if (material) {
  20215. // Render targets
  20216. if (material.getRenderTargetTextures) {
  20217. if (this._processedMaterials.indexOf(material) === -1) {
  20218. this._processedMaterials.push(material);
  20219. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20220. }
  20221. }
  20222. // Dispatch
  20223. this._activeIndices.addCount(subMesh.indexCount, false);
  20224. this._renderingManager.dispatch(subMesh);
  20225. }
  20226. }
  20227. };
  20228. Scene.prototype._isInIntermediateRendering = function () {
  20229. return this._intermediateRendering;
  20230. };
  20231. /**
  20232. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20233. */
  20234. Scene.prototype.freezeActiveMeshes = function () {
  20235. this._evaluateActiveMeshes();
  20236. this._activeMeshesFrozen = true;
  20237. return this;
  20238. };
  20239. /**
  20240. * Use this function to restart evaluating active meshes on every frame
  20241. */
  20242. Scene.prototype.unfreezeActiveMeshes = function () {
  20243. this._activeMeshesFrozen = false;
  20244. return this;
  20245. };
  20246. Scene.prototype._evaluateActiveMeshes = function () {
  20247. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20248. return;
  20249. }
  20250. if (!this.activeCamera) {
  20251. return;
  20252. }
  20253. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20254. this.activeCamera._activeMeshes.reset();
  20255. this._activeMeshes.reset();
  20256. this._renderingManager.reset();
  20257. this._processedMaterials.reset();
  20258. this._activeParticleSystems.reset();
  20259. this._activeSkeletons.reset();
  20260. this._softwareSkinnedMeshes.reset();
  20261. if (this._boundingBoxRenderer) {
  20262. this._boundingBoxRenderer.reset();
  20263. }
  20264. // Meshes
  20265. var meshes;
  20266. var len;
  20267. if (this._selectionOctree) {
  20268. var selection = this._selectionOctree.select(this._frustumPlanes);
  20269. meshes = selection.data;
  20270. len = selection.length;
  20271. }
  20272. else {
  20273. len = this.meshes.length;
  20274. meshes = this.meshes;
  20275. }
  20276. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20277. var mesh = meshes[meshIndex];
  20278. if (mesh.isBlocked) {
  20279. continue;
  20280. }
  20281. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20282. if (!mesh.isReady() || !mesh.isEnabled()) {
  20283. continue;
  20284. }
  20285. mesh.computeWorldMatrix();
  20286. // Intersections
  20287. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20288. this._meshesForIntersections.pushNoDuplicate(mesh);
  20289. }
  20290. // Switch to current LOD
  20291. var meshLOD = mesh.getLOD(this.activeCamera);
  20292. if (!meshLOD) {
  20293. continue;
  20294. }
  20295. mesh._preActivate();
  20296. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20297. this._activeMeshes.push(mesh);
  20298. this.activeCamera._activeMeshes.push(mesh);
  20299. mesh._activate(this._renderId);
  20300. if (meshLOD !== mesh) {
  20301. meshLOD._activate(this._renderId);
  20302. }
  20303. this._activeMesh(mesh, meshLOD);
  20304. }
  20305. }
  20306. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20307. // Particle systems
  20308. if (this.particlesEnabled) {
  20309. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20310. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20311. var particleSystem = this.particleSystems[particleIndex];
  20312. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20313. continue;
  20314. }
  20315. var emitter = particleSystem.emitter;
  20316. if (!emitter.position || emitter.isEnabled()) {
  20317. this._activeParticleSystems.push(particleSystem);
  20318. particleSystem.animate();
  20319. this._renderingManager.dispatchParticles(particleSystem);
  20320. }
  20321. }
  20322. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20323. }
  20324. };
  20325. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20326. if (mesh.skeleton && this.skeletonsEnabled) {
  20327. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20328. mesh.skeleton.prepare();
  20329. }
  20330. if (!mesh.computeBonesUsingShaders) {
  20331. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20332. }
  20333. }
  20334. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20335. var boundingInfo = sourceMesh.getBoundingInfo();
  20336. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20337. }
  20338. if (mesh && mesh.subMeshes) {
  20339. // Submeshes Octrees
  20340. var len;
  20341. var subMeshes;
  20342. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20343. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20344. len = intersections.length;
  20345. subMeshes = intersections.data;
  20346. }
  20347. else {
  20348. subMeshes = mesh.subMeshes;
  20349. len = subMeshes.length;
  20350. }
  20351. for (var subIndex = 0; subIndex < len; subIndex++) {
  20352. var subMesh = subMeshes[subIndex];
  20353. this._evaluateSubMesh(subMesh, mesh);
  20354. }
  20355. }
  20356. };
  20357. Scene.prototype.updateTransformMatrix = function (force) {
  20358. if (!this.activeCamera) {
  20359. return;
  20360. }
  20361. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20362. };
  20363. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20364. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20365. };
  20366. Scene.prototype._renderForCamera = function (camera) {
  20367. if (camera && camera._skipRendering) {
  20368. return;
  20369. }
  20370. var engine = this._engine;
  20371. this.activeCamera = camera;
  20372. if (!this.activeCamera)
  20373. throw new Error("Active camera not set");
  20374. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20375. // Viewport
  20376. engine.setViewport(this.activeCamera.viewport);
  20377. // Camera
  20378. this.resetCachedMaterial();
  20379. this._renderId++;
  20380. this.activeCamera.update();
  20381. this.updateTransformMatrix();
  20382. if (camera._alternateCamera) {
  20383. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20384. this._alternateRendering = true;
  20385. }
  20386. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20387. // Meshes
  20388. this._evaluateActiveMeshes();
  20389. // Software skinning
  20390. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20391. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20392. mesh.applySkeleton(mesh.skeleton);
  20393. }
  20394. // Render targets
  20395. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20396. var needsRestoreFrameBuffer = false;
  20397. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20398. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20399. }
  20400. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20401. this._intermediateRendering = true;
  20402. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20403. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20404. var renderTarget = this._renderTargets.data[renderIndex];
  20405. if (renderTarget._shouldRender()) {
  20406. this._renderId++;
  20407. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20408. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20409. }
  20410. }
  20411. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20412. this._intermediateRendering = false;
  20413. this._renderId++;
  20414. needsRestoreFrameBuffer = true; // Restore back buffer
  20415. }
  20416. // Render HighlightLayer Texture
  20417. var stencilState = this._engine.getStencilBuffer();
  20418. var renderhighlights = false;
  20419. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20420. this._intermediateRendering = true;
  20421. for (var i = 0; i < this.highlightLayers.length; i++) {
  20422. var highlightLayer = this.highlightLayers[i];
  20423. if (highlightLayer.shouldRender() &&
  20424. (!highlightLayer.camera ||
  20425. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20426. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20427. renderhighlights = true;
  20428. var renderTarget = highlightLayer._mainTexture;
  20429. if (renderTarget._shouldRender()) {
  20430. this._renderId++;
  20431. renderTarget.render(false, false);
  20432. needsRestoreFrameBuffer = true;
  20433. }
  20434. }
  20435. }
  20436. this._intermediateRendering = false;
  20437. this._renderId++;
  20438. }
  20439. if (needsRestoreFrameBuffer) {
  20440. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20441. }
  20442. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20443. // Prepare Frame
  20444. this.postProcessManager._prepareFrame();
  20445. // Backgrounds
  20446. var layerIndex;
  20447. var layer;
  20448. if (this.layers.length) {
  20449. engine.setDepthBuffer(false);
  20450. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20451. layer = this.layers[layerIndex];
  20452. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20453. layer.render();
  20454. }
  20455. }
  20456. engine.setDepthBuffer(true);
  20457. }
  20458. // Activate HighlightLayer stencil
  20459. if (renderhighlights) {
  20460. this._engine.setStencilBuffer(true);
  20461. }
  20462. // Render
  20463. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20464. this._renderingManager.render(null, null, true, true);
  20465. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20466. // Restore HighlightLayer stencil
  20467. if (renderhighlights) {
  20468. this._engine.setStencilBuffer(stencilState);
  20469. }
  20470. // Bounding boxes
  20471. if (this._boundingBoxRenderer) {
  20472. this._boundingBoxRenderer.render();
  20473. }
  20474. // Lens flares
  20475. if (this.lensFlaresEnabled) {
  20476. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20477. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20478. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20479. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20480. lensFlareSystem.render();
  20481. }
  20482. }
  20483. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20484. }
  20485. // Foregrounds
  20486. if (this.layers.length) {
  20487. engine.setDepthBuffer(false);
  20488. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20489. layer = this.layers[layerIndex];
  20490. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20491. layer.render();
  20492. }
  20493. }
  20494. engine.setDepthBuffer(true);
  20495. }
  20496. // Highlight Layer
  20497. if (renderhighlights) {
  20498. engine.setDepthBuffer(false);
  20499. for (var i = 0; i < this.highlightLayers.length; i++) {
  20500. if (this.highlightLayers[i].shouldRender()) {
  20501. this.highlightLayers[i].render();
  20502. }
  20503. }
  20504. engine.setDepthBuffer(true);
  20505. }
  20506. // Finalize frame
  20507. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20508. // Reset some special arrays
  20509. this._renderTargets.reset();
  20510. this._alternateRendering = false;
  20511. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20512. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20513. };
  20514. Scene.prototype._processSubCameras = function (camera) {
  20515. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20516. this._renderForCamera(camera);
  20517. return;
  20518. }
  20519. // Update camera
  20520. if (this.activeCamera) {
  20521. this.activeCamera.update();
  20522. }
  20523. // rig cameras
  20524. for (var index = 0; index < camera._rigCameras.length; index++) {
  20525. this._renderForCamera(camera._rigCameras[index]);
  20526. }
  20527. this.activeCamera = camera;
  20528. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20529. };
  20530. Scene.prototype._checkIntersections = function () {
  20531. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20532. var sourceMesh = this._meshesForIntersections.data[index];
  20533. if (!sourceMesh.actionManager) {
  20534. continue;
  20535. }
  20536. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20537. var action = sourceMesh.actionManager.actions[actionIndex];
  20538. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20539. var parameters = action.getTriggerParameter();
  20540. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20541. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20542. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20543. if (areIntersecting && currentIntersectionInProgress === -1) {
  20544. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20545. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20546. sourceMesh._intersectionsInProgress.push(otherMesh);
  20547. }
  20548. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20549. sourceMesh._intersectionsInProgress.push(otherMesh);
  20550. }
  20551. }
  20552. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20553. //They intersected, and now they don't.
  20554. //is this trigger an exit trigger? execute an event.
  20555. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20556. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20557. }
  20558. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20559. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20560. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20561. }
  20562. }
  20563. }
  20564. }
  20565. }
  20566. };
  20567. Scene.prototype.render = function () {
  20568. if (this.isDisposed) {
  20569. return;
  20570. }
  20571. this._activeParticles.fetchNewFrame();
  20572. this._totalVertices.fetchNewFrame();
  20573. this._activeIndices.fetchNewFrame();
  20574. this._activeBones.fetchNewFrame();
  20575. this._meshesForIntersections.reset();
  20576. this.resetCachedMaterial();
  20577. this.onBeforeAnimationsObservable.notifyObservers(this);
  20578. // Actions
  20579. if (this.actionManager) {
  20580. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20581. }
  20582. //Simplification Queue
  20583. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20584. this.simplificationQueue.executeNext();
  20585. }
  20586. if (this._engine.isDeterministicLockStep()) {
  20587. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20588. var defaultFPS = (60.0 / 1000.0);
  20589. var defaultFrameTime = 1000 / 60; // frame time in MS
  20590. if (this._physicsEngine) {
  20591. defaultFrameTime = this._physicsEngine.getTimeStep() / 1000; //timestep in physics engine is in seconds
  20592. }
  20593. var stepsTaken = 0;
  20594. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20595. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20596. internalSteps = Math.min(internalSteps, maxSubSteps);
  20597. do {
  20598. this.onBeforeStepObservable.notifyObservers(this);
  20599. // Animations
  20600. this._animationRatio = defaultFrameTime * defaultFPS;
  20601. this._animate();
  20602. this.onAfterAnimationsObservable.notifyObservers(this);
  20603. // Physics
  20604. if (this._physicsEngine) {
  20605. this.onBeforePhysicsObservable.notifyObservers(this);
  20606. this._physicsEngine._step(defaultFPS);
  20607. this.onAfterPhysicsObservable.notifyObservers(this);
  20608. }
  20609. this.onAfterStepObservable.notifyObservers(this);
  20610. this._currentStepId++;
  20611. if ((internalSteps > 1) && (stepsTaken != internalSteps - 1)) {
  20612. this._evaluateActiveMeshes();
  20613. }
  20614. stepsTaken++;
  20615. deltaTime -= defaultFrameTime;
  20616. } while (deltaTime > 0 && stepsTaken < maxSubSteps);
  20617. this._timeAccumulator = deltaTime;
  20618. }
  20619. else {
  20620. // Animations
  20621. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20622. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20623. this._animate();
  20624. this.onAfterAnimationsObservable.notifyObservers(this);
  20625. // Physics
  20626. if (this._physicsEngine) {
  20627. this.onBeforePhysicsObservable.notifyObservers(this);
  20628. this._physicsEngine._step(deltaTime / 1000.0);
  20629. this.onAfterPhysicsObservable.notifyObservers(this);
  20630. }
  20631. }
  20632. // update gamepad manager
  20633. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20634. this._gamepadManager._checkGamepadsStatus();
  20635. }
  20636. // Before render
  20637. this.onBeforeRenderObservable.notifyObservers(this);
  20638. // Customs render targets
  20639. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20640. var engine = this.getEngine();
  20641. var currentActiveCamera = this.activeCamera;
  20642. if (this.renderTargetsEnabled) {
  20643. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20644. this._intermediateRendering = true;
  20645. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20646. var renderTarget = this.customRenderTargets[customIndex];
  20647. if (renderTarget._shouldRender()) {
  20648. this._renderId++;
  20649. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20650. if (!this.activeCamera)
  20651. throw new Error("Active camera not set");
  20652. // Viewport
  20653. engine.setViewport(this.activeCamera.viewport);
  20654. // Camera
  20655. this.updateTransformMatrix();
  20656. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20657. }
  20658. }
  20659. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20660. this._intermediateRendering = false;
  20661. this._renderId++;
  20662. }
  20663. // Restore back buffer
  20664. if (this.customRenderTargets.length > 0) {
  20665. engine.restoreDefaultFramebuffer();
  20666. }
  20667. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20668. this.activeCamera = currentActiveCamera;
  20669. // Procedural textures
  20670. if (this.proceduralTexturesEnabled) {
  20671. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20672. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20673. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20674. if (proceduralTexture._shouldRender()) {
  20675. proceduralTexture.render();
  20676. }
  20677. }
  20678. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20679. }
  20680. // Clear
  20681. if (this.autoClearDepthAndStencil || this.autoClear) {
  20682. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20683. }
  20684. // Shadows
  20685. if (this.shadowsEnabled) {
  20686. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20687. var light = this.lights[lightIndex];
  20688. var shadowGenerator = light.getShadowGenerator();
  20689. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20690. var shadowMap = (shadowGenerator.getShadowMap());
  20691. if (this.textures.indexOf(shadowMap) !== -1) {
  20692. this._renderTargets.push(shadowMap);
  20693. }
  20694. }
  20695. }
  20696. }
  20697. // Depth renderer
  20698. if (this._depthRenderer) {
  20699. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20700. }
  20701. // Geometry renderer
  20702. if (this._geometryBufferRenderer) {
  20703. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20704. }
  20705. // RenderPipeline
  20706. if (this._postProcessRenderPipelineManager) {
  20707. this._postProcessRenderPipelineManager.update();
  20708. }
  20709. // Multi-cameras?
  20710. if (this.activeCameras.length > 0) {
  20711. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20712. if (cameraIndex > 0) {
  20713. this._engine.clear(null, false, true, true);
  20714. }
  20715. this._processSubCameras(this.activeCameras[cameraIndex]);
  20716. }
  20717. }
  20718. else {
  20719. if (!this.activeCamera) {
  20720. throw new Error("No camera defined");
  20721. }
  20722. this._processSubCameras(this.activeCamera);
  20723. }
  20724. // Intersection checks
  20725. this._checkIntersections();
  20726. // Update the audio listener attached to the camera
  20727. if (BABYLON.AudioEngine) {
  20728. this._updateAudioParameters();
  20729. }
  20730. // After render
  20731. if (this.afterRender) {
  20732. this.afterRender();
  20733. }
  20734. this.onAfterRenderObservable.notifyObservers(this);
  20735. // Cleaning
  20736. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20737. var data = this._toBeDisposed.data[index];
  20738. if (data) {
  20739. data.dispose();
  20740. }
  20741. this._toBeDisposed[index] = null;
  20742. }
  20743. this._toBeDisposed.reset();
  20744. if (this.dumpNextRenderTargets) {
  20745. this.dumpNextRenderTargets = false;
  20746. }
  20747. this._activeBones.addCount(0, true);
  20748. this._activeIndices.addCount(0, true);
  20749. this._activeParticles.addCount(0, true);
  20750. };
  20751. Scene.prototype._updateAudioParameters = function () {
  20752. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20753. return;
  20754. }
  20755. var listeningCamera;
  20756. var audioEngine = BABYLON.Engine.audioEngine;
  20757. if (this.activeCameras.length > 0) {
  20758. listeningCamera = this.activeCameras[0];
  20759. }
  20760. else {
  20761. listeningCamera = this.activeCamera;
  20762. }
  20763. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20764. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20765. // for VR cameras
  20766. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20767. listeningCamera = listeningCamera.rigCameras[0];
  20768. }
  20769. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20770. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20771. cameraDirection.normalize();
  20772. // To avoid some errors on GearVR
  20773. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20774. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20775. }
  20776. var i;
  20777. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20778. var sound = this.mainSoundTrack.soundCollection[i];
  20779. if (sound.useCustomAttenuation) {
  20780. sound.updateDistanceFromListener();
  20781. }
  20782. }
  20783. for (i = 0; i < this.soundTracks.length; i++) {
  20784. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20785. sound = this.soundTracks[i].soundCollection[j];
  20786. if (sound.useCustomAttenuation) {
  20787. sound.updateDistanceFromListener();
  20788. }
  20789. }
  20790. }
  20791. }
  20792. };
  20793. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20794. // Audio
  20795. get: function () {
  20796. return this._audioEnabled;
  20797. },
  20798. set: function (value) {
  20799. this._audioEnabled = value;
  20800. if (BABYLON.AudioEngine) {
  20801. if (this._audioEnabled) {
  20802. this._enableAudio();
  20803. }
  20804. else {
  20805. this._disableAudio();
  20806. }
  20807. }
  20808. },
  20809. enumerable: true,
  20810. configurable: true
  20811. });
  20812. Scene.prototype._disableAudio = function () {
  20813. var i;
  20814. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20815. this.mainSoundTrack.soundCollection[i].pause();
  20816. }
  20817. for (i = 0; i < this.soundTracks.length; i++) {
  20818. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20819. this.soundTracks[i].soundCollection[j].pause();
  20820. }
  20821. }
  20822. };
  20823. Scene.prototype._enableAudio = function () {
  20824. var i;
  20825. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20826. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20827. this.mainSoundTrack.soundCollection[i].play();
  20828. }
  20829. }
  20830. for (i = 0; i < this.soundTracks.length; i++) {
  20831. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20832. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20833. this.soundTracks[i].soundCollection[j].play();
  20834. }
  20835. }
  20836. }
  20837. };
  20838. Object.defineProperty(Scene.prototype, "headphone", {
  20839. get: function () {
  20840. return this._headphone;
  20841. },
  20842. set: function (value) {
  20843. this._headphone = value;
  20844. if (BABYLON.AudioEngine) {
  20845. if (this._headphone) {
  20846. this._switchAudioModeForHeadphones();
  20847. }
  20848. else {
  20849. this._switchAudioModeForNormalSpeakers();
  20850. }
  20851. }
  20852. },
  20853. enumerable: true,
  20854. configurable: true
  20855. });
  20856. Scene.prototype._switchAudioModeForHeadphones = function () {
  20857. this.mainSoundTrack.switchPanningModelToHRTF();
  20858. for (var i = 0; i < this.soundTracks.length; i++) {
  20859. this.soundTracks[i].switchPanningModelToHRTF();
  20860. }
  20861. };
  20862. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20863. this.mainSoundTrack.switchPanningModelToEqualPower();
  20864. for (var i = 0; i < this.soundTracks.length; i++) {
  20865. this.soundTracks[i].switchPanningModelToEqualPower();
  20866. }
  20867. };
  20868. Scene.prototype.enableDepthRenderer = function () {
  20869. if (this._depthRenderer) {
  20870. return this._depthRenderer;
  20871. }
  20872. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20873. return this._depthRenderer;
  20874. };
  20875. Scene.prototype.disableDepthRenderer = function () {
  20876. if (!this._depthRenderer) {
  20877. return;
  20878. }
  20879. this._depthRenderer.dispose();
  20880. this._depthRenderer = null;
  20881. };
  20882. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20883. if (ratio === void 0) { ratio = 1; }
  20884. if (this._geometryBufferRenderer) {
  20885. return this._geometryBufferRenderer;
  20886. }
  20887. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20888. if (!this._geometryBufferRenderer.isSupported) {
  20889. this._geometryBufferRenderer = null;
  20890. }
  20891. return this._geometryBufferRenderer;
  20892. };
  20893. Scene.prototype.disableGeometryBufferRenderer = function () {
  20894. if (!this._geometryBufferRenderer) {
  20895. return;
  20896. }
  20897. this._geometryBufferRenderer.dispose();
  20898. this._geometryBufferRenderer = null;
  20899. };
  20900. Scene.prototype.freezeMaterials = function () {
  20901. for (var i = 0; i < this.materials.length; i++) {
  20902. this.materials[i].freeze();
  20903. }
  20904. };
  20905. Scene.prototype.unfreezeMaterials = function () {
  20906. for (var i = 0; i < this.materials.length; i++) {
  20907. this.materials[i].unfreeze();
  20908. }
  20909. };
  20910. Scene.prototype.dispose = function () {
  20911. this.beforeRender = null;
  20912. this.afterRender = null;
  20913. this.skeletons = [];
  20914. this.morphTargetManagers = [];
  20915. this.importedMeshesFiles = new Array();
  20916. this.stopAllAnimations();
  20917. this.resetCachedMaterial();
  20918. if (this._depthRenderer) {
  20919. this._depthRenderer.dispose();
  20920. }
  20921. if (this._gamepadManager) {
  20922. this._gamepadManager.dispose();
  20923. this._gamepadManager = null;
  20924. }
  20925. // Smart arrays
  20926. if (this.activeCamera) {
  20927. this.activeCamera._activeMeshes.dispose();
  20928. this.activeCamera = null;
  20929. }
  20930. this._activeMeshes.dispose();
  20931. this._renderingManager.dispose();
  20932. this._processedMaterials.dispose();
  20933. this._activeParticleSystems.dispose();
  20934. this._activeSkeletons.dispose();
  20935. this._softwareSkinnedMeshes.dispose();
  20936. this._renderTargets.dispose();
  20937. if (this._boundingBoxRenderer) {
  20938. this._boundingBoxRenderer.dispose();
  20939. }
  20940. this._meshesForIntersections.dispose();
  20941. this._toBeDisposed.dispose();
  20942. // Debug layer
  20943. if (this._debugLayer) {
  20944. this._debugLayer.hide();
  20945. }
  20946. // Events
  20947. this.onDisposeObservable.notifyObservers(this);
  20948. this.onDisposeObservable.clear();
  20949. this.onBeforeRenderObservable.clear();
  20950. this.onAfterRenderObservable.clear();
  20951. this.OnBeforeRenderTargetsRenderObservable.clear();
  20952. this.OnAfterRenderTargetsRenderObservable.clear();
  20953. this.onAfterStepObservable.clear();
  20954. this.onBeforeStepObservable.clear();
  20955. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20956. this.onAfterActiveMeshesEvaluationObservable.clear();
  20957. this.onBeforeParticlesRenderingObservable.clear();
  20958. this.onAfterParticlesRenderingObservable.clear();
  20959. this.onBeforeSpritesRenderingObservable.clear();
  20960. this.onAfterSpritesRenderingObservable.clear();
  20961. this.onBeforeDrawPhaseObservable.clear();
  20962. this.onAfterDrawPhaseObservable.clear();
  20963. this.onBeforePhysicsObservable.clear();
  20964. this.onAfterPhysicsObservable.clear();
  20965. this.onBeforeAnimationsObservable.clear();
  20966. this.onAfterAnimationsObservable.clear();
  20967. this.onDataLoadedObservable.clear();
  20968. this.detachControl();
  20969. // Release sounds & sounds tracks
  20970. if (BABYLON.AudioEngine) {
  20971. this.disposeSounds();
  20972. }
  20973. // VR Helper
  20974. if (this.VRHelper) {
  20975. this.VRHelper.dispose();
  20976. }
  20977. // Detach cameras
  20978. var canvas = this._engine.getRenderingCanvas();
  20979. if (canvas) {
  20980. var index;
  20981. for (index = 0; index < this.cameras.length; index++) {
  20982. this.cameras[index].detachControl(canvas);
  20983. }
  20984. }
  20985. // Release lights
  20986. while (this.lights.length) {
  20987. this.lights[0].dispose();
  20988. }
  20989. // Release meshes
  20990. while (this.meshes.length) {
  20991. this.meshes[0].dispose(true);
  20992. }
  20993. while (this.transformNodes.length) {
  20994. this.removeTransformNode(this.transformNodes[0]);
  20995. }
  20996. // Release cameras
  20997. while (this.cameras.length) {
  20998. this.cameras[0].dispose();
  20999. }
  21000. // Release materials
  21001. if (this.defaultMaterial) {
  21002. this.defaultMaterial.dispose();
  21003. }
  21004. while (this.multiMaterials.length) {
  21005. this.multiMaterials[0].dispose();
  21006. }
  21007. while (this.materials.length) {
  21008. this.materials[0].dispose();
  21009. }
  21010. // Release particles
  21011. while (this.particleSystems.length) {
  21012. this.particleSystems[0].dispose();
  21013. }
  21014. // Release sprites
  21015. while (this.spriteManagers.length) {
  21016. this.spriteManagers[0].dispose();
  21017. }
  21018. // Release postProcesses
  21019. while (this.postProcesses.length) {
  21020. this.postProcesses[0].dispose();
  21021. }
  21022. // Release layers
  21023. while (this.layers.length) {
  21024. this.layers[0].dispose();
  21025. }
  21026. while (this.highlightLayers.length) {
  21027. this.highlightLayers[0].dispose();
  21028. }
  21029. // Release textures
  21030. while (this.textures.length) {
  21031. this.textures[0].dispose();
  21032. }
  21033. // Release UBO
  21034. this._sceneUbo.dispose();
  21035. if (this._alternateSceneUbo) {
  21036. this._alternateSceneUbo.dispose();
  21037. }
  21038. // Post-processes
  21039. this.postProcessManager.dispose();
  21040. if (this._postProcessRenderPipelineManager) {
  21041. this._postProcessRenderPipelineManager.dispose();
  21042. }
  21043. // Physics
  21044. if (this._physicsEngine) {
  21045. this.disablePhysicsEngine();
  21046. }
  21047. // Remove from engine
  21048. index = this._engine.scenes.indexOf(this);
  21049. if (index > -1) {
  21050. this._engine.scenes.splice(index, 1);
  21051. }
  21052. this._engine.wipeCaches();
  21053. this._isDisposed = true;
  21054. };
  21055. Object.defineProperty(Scene.prototype, "isDisposed", {
  21056. get: function () {
  21057. return this._isDisposed;
  21058. },
  21059. enumerable: true,
  21060. configurable: true
  21061. });
  21062. // Release sounds & sounds tracks
  21063. Scene.prototype.disposeSounds = function () {
  21064. if (!this._mainSoundTrack) {
  21065. return;
  21066. }
  21067. this.mainSoundTrack.dispose();
  21068. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21069. this.soundTracks[scIndex].dispose();
  21070. }
  21071. };
  21072. // Octrees
  21073. Scene.prototype.getWorldExtends = function () {
  21074. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21075. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21076. for (var index = 0; index < this.meshes.length; index++) {
  21077. var mesh = this.meshes[index];
  21078. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21079. continue;
  21080. }
  21081. mesh.computeWorldMatrix(true);
  21082. var boundingInfo = mesh.getBoundingInfo();
  21083. var minBox = boundingInfo.boundingBox.minimumWorld;
  21084. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21085. BABYLON.Tools.CheckExtends(minBox, min, max);
  21086. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21087. }
  21088. return {
  21089. min: min,
  21090. max: max
  21091. };
  21092. };
  21093. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21094. if (maxCapacity === void 0) { maxCapacity = 64; }
  21095. if (maxDepth === void 0) { maxDepth = 2; }
  21096. if (!this._selectionOctree) {
  21097. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21098. }
  21099. var worldExtends = this.getWorldExtends();
  21100. // Update octree
  21101. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21102. return this._selectionOctree;
  21103. };
  21104. // Picking
  21105. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21106. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21107. var result = BABYLON.Ray.Zero();
  21108. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21109. return result;
  21110. };
  21111. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21112. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21113. var engine = this._engine;
  21114. if (!camera) {
  21115. if (!this.activeCamera)
  21116. throw new Error("Active camera not set");
  21117. camera = this.activeCamera;
  21118. }
  21119. var cameraViewport = camera.viewport;
  21120. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21121. // Moving coordinates to local viewport world
  21122. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21123. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21124. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21125. return this;
  21126. };
  21127. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21128. var result = BABYLON.Ray.Zero();
  21129. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21130. return result;
  21131. };
  21132. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21133. if (!BABYLON.PickingInfo) {
  21134. return this;
  21135. }
  21136. var engine = this._engine;
  21137. if (!camera) {
  21138. if (!this.activeCamera)
  21139. throw new Error("Active camera not set");
  21140. camera = this.activeCamera;
  21141. }
  21142. var cameraViewport = camera.viewport;
  21143. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21144. var identity = BABYLON.Matrix.Identity();
  21145. // Moving coordinates to local viewport world
  21146. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21147. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21148. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21149. return this;
  21150. };
  21151. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21152. if (!BABYLON.PickingInfo) {
  21153. return null;
  21154. }
  21155. var pickingInfo = null;
  21156. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21157. var mesh = this.meshes[meshIndex];
  21158. if (predicate) {
  21159. if (!predicate(mesh)) {
  21160. continue;
  21161. }
  21162. }
  21163. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21164. continue;
  21165. }
  21166. var world = mesh.getWorldMatrix();
  21167. var ray = rayFunction(world);
  21168. var result = mesh.intersects(ray, fastCheck);
  21169. if (!result || !result.hit)
  21170. continue;
  21171. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21172. continue;
  21173. pickingInfo = result;
  21174. if (fastCheck) {
  21175. break;
  21176. }
  21177. }
  21178. return pickingInfo || new BABYLON.PickingInfo();
  21179. };
  21180. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21181. if (!BABYLON.PickingInfo) {
  21182. return null;
  21183. }
  21184. var pickingInfos = new Array();
  21185. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21186. var mesh = this.meshes[meshIndex];
  21187. if (predicate) {
  21188. if (!predicate(mesh)) {
  21189. continue;
  21190. }
  21191. }
  21192. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21193. continue;
  21194. }
  21195. var world = mesh.getWorldMatrix();
  21196. var ray = rayFunction(world);
  21197. var result = mesh.intersects(ray, false);
  21198. if (!result || !result.hit)
  21199. continue;
  21200. pickingInfos.push(result);
  21201. }
  21202. return pickingInfos;
  21203. };
  21204. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21205. if (!BABYLON.PickingInfo) {
  21206. return null;
  21207. }
  21208. var pickingInfo = null;
  21209. if (!camera) {
  21210. if (!this.activeCamera) {
  21211. return null;
  21212. }
  21213. camera = this.activeCamera;
  21214. }
  21215. if (this.spriteManagers.length > 0) {
  21216. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21217. var spriteManager = this.spriteManagers[spriteIndex];
  21218. if (!spriteManager.isPickable) {
  21219. continue;
  21220. }
  21221. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21222. if (!result || !result.hit)
  21223. continue;
  21224. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21225. continue;
  21226. pickingInfo = result;
  21227. if (fastCheck) {
  21228. break;
  21229. }
  21230. }
  21231. }
  21232. return pickingInfo || new BABYLON.PickingInfo();
  21233. };
  21234. /** Launch a ray to try to pick a mesh in the scene
  21235. * @param x position on screen
  21236. * @param y position on screen
  21237. * @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
  21238. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21239. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21240. */
  21241. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21242. var _this = this;
  21243. if (!BABYLON.PickingInfo) {
  21244. return null;
  21245. }
  21246. return this._internalPick(function (world) {
  21247. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21248. return _this._tempPickingRay;
  21249. }, predicate, fastCheck);
  21250. };
  21251. /** Launch a ray to try to pick a sprite in the scene
  21252. * @param x position on screen
  21253. * @param y position on screen
  21254. * @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
  21255. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21256. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21257. */
  21258. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21259. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21260. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21261. };
  21262. /** Use the given ray to pick a mesh in the scene
  21263. * @param ray The ray to use to pick meshes
  21264. * @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
  21265. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21266. */
  21267. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21268. var _this = this;
  21269. return this._internalPick(function (world) {
  21270. if (!_this._pickWithRayInverseMatrix) {
  21271. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21272. }
  21273. world.invertToRef(_this._pickWithRayInverseMatrix);
  21274. if (!_this._cachedRayForTransform) {
  21275. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21276. }
  21277. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21278. return _this._cachedRayForTransform;
  21279. }, predicate, fastCheck);
  21280. };
  21281. /**
  21282. * Launch a ray to try to pick a mesh in the scene
  21283. * @param x X position on screen
  21284. * @param y Y position on screen
  21285. * @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
  21286. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21287. */
  21288. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21289. var _this = this;
  21290. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21291. };
  21292. /**
  21293. * Launch a ray to try to pick a mesh in the scene
  21294. * @param ray Ray to use
  21295. * @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
  21296. */
  21297. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21298. var _this = this;
  21299. return this._internalMultiPick(function (world) {
  21300. if (!_this._pickWithRayInverseMatrix) {
  21301. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21302. }
  21303. world.invertToRef(_this._pickWithRayInverseMatrix);
  21304. if (!_this._cachedRayForTransform) {
  21305. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21306. }
  21307. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21308. return _this._cachedRayForTransform;
  21309. }, predicate);
  21310. };
  21311. Scene.prototype.setPointerOverMesh = function (mesh) {
  21312. if (this._pointerOverMesh === mesh) {
  21313. return;
  21314. }
  21315. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21316. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21317. }
  21318. this._pointerOverMesh = mesh;
  21319. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21320. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21321. }
  21322. };
  21323. Scene.prototype.getPointerOverMesh = function () {
  21324. return this._pointerOverMesh;
  21325. };
  21326. Scene.prototype.setPointerOverSprite = function (sprite) {
  21327. if (this._pointerOverSprite === sprite) {
  21328. return;
  21329. }
  21330. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21331. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21332. }
  21333. this._pointerOverSprite = sprite;
  21334. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21335. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21336. }
  21337. };
  21338. Scene.prototype.getPointerOverSprite = function () {
  21339. return this._pointerOverSprite;
  21340. };
  21341. // Physics
  21342. Scene.prototype.getPhysicsEngine = function () {
  21343. return this._physicsEngine;
  21344. };
  21345. /**
  21346. * Enables physics to the current scene
  21347. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21348. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21349. * @return {boolean} was the physics engine initialized
  21350. */
  21351. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21352. if (gravity === void 0) { gravity = null; }
  21353. if (this._physicsEngine) {
  21354. return true;
  21355. }
  21356. try {
  21357. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21358. return true;
  21359. }
  21360. catch (e) {
  21361. BABYLON.Tools.Error(e.message);
  21362. return false;
  21363. }
  21364. };
  21365. Scene.prototype.disablePhysicsEngine = function () {
  21366. if (!this._physicsEngine) {
  21367. return;
  21368. }
  21369. this._physicsEngine.dispose();
  21370. this._physicsEngine = null;
  21371. };
  21372. Scene.prototype.isPhysicsEnabled = function () {
  21373. return this._physicsEngine !== undefined;
  21374. };
  21375. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21376. var mesh = compound.parts[0].mesh;
  21377. if (mesh.physicsImpostor) {
  21378. mesh.physicsImpostor.dispose();
  21379. mesh.physicsImpostor = null;
  21380. }
  21381. };
  21382. // Misc.
  21383. Scene.prototype._rebuildGeometries = function () {
  21384. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21385. var geometry = _a[_i];
  21386. geometry._rebuild();
  21387. }
  21388. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21389. var mesh = _c[_b];
  21390. mesh._rebuild();
  21391. }
  21392. if (this.postProcessManager) {
  21393. this.postProcessManager._rebuild();
  21394. }
  21395. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21396. var layer = _e[_d];
  21397. layer._rebuild();
  21398. }
  21399. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21400. var highlightLayer = _g[_f];
  21401. highlightLayer._rebuild();
  21402. }
  21403. if (this._boundingBoxRenderer) {
  21404. this._boundingBoxRenderer._rebuild();
  21405. }
  21406. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21407. var system = _j[_h];
  21408. system.rebuild();
  21409. }
  21410. if (this._postProcessRenderPipelineManager) {
  21411. this._postProcessRenderPipelineManager._rebuild();
  21412. }
  21413. };
  21414. Scene.prototype._rebuildTextures = function () {
  21415. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21416. var texture = _a[_i];
  21417. texture._rebuild();
  21418. }
  21419. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21420. };
  21421. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21422. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21423. if (replace === void 0) { replace = false; }
  21424. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21425. // Dispose existing camera or light in replace mode.
  21426. if (replace) {
  21427. if (this.activeCamera) {
  21428. this.activeCamera.dispose();
  21429. this.activeCamera = null;
  21430. }
  21431. if (this.lights) {
  21432. for (var i = 0; i < this.lights.length; i++) {
  21433. this.lights[i].dispose();
  21434. }
  21435. }
  21436. }
  21437. // Light
  21438. if (this.lights.length === 0) {
  21439. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21440. }
  21441. // Camera
  21442. if (!this.activeCamera) {
  21443. var worldExtends = this.getWorldExtends();
  21444. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21445. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21446. var camera;
  21447. var radius = worldSize.length() * 1.5;
  21448. if (createArcRotateCamera) {
  21449. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21450. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21451. arcRotateCamera.wheelPrecision = 100 / radius;
  21452. camera = arcRotateCamera;
  21453. }
  21454. else {
  21455. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21456. freeCamera.setTarget(worldCenter);
  21457. camera = freeCamera;
  21458. }
  21459. camera.minZ = radius * 0.01;
  21460. camera.maxZ = radius * 100;
  21461. camera.speed = radius * 0.2;
  21462. this.activeCamera = camera;
  21463. var canvas = this.getEngine().getRenderingCanvas();
  21464. if (attachCameraControls && canvas) {
  21465. camera.attachControl(canvas);
  21466. }
  21467. }
  21468. };
  21469. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21470. if (pbr === void 0) { pbr = false; }
  21471. if (scale === void 0) { scale = 1000; }
  21472. if (blur === void 0) { blur = 0; }
  21473. if (environmentTexture) {
  21474. this.environmentTexture = environmentTexture;
  21475. }
  21476. if (!this.environmentTexture) {
  21477. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21478. return null;
  21479. }
  21480. // Skybox
  21481. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21482. if (pbr) {
  21483. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21484. hdrSkyboxMaterial.backFaceCulling = false;
  21485. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21486. if (hdrSkyboxMaterial.reflectionTexture) {
  21487. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21488. }
  21489. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21490. hdrSkyboxMaterial.disableLighting = true;
  21491. hdrSkyboxMaterial.twoSidedLighting = true;
  21492. hdrSkybox.infiniteDistance = true;
  21493. hdrSkybox.material = hdrSkyboxMaterial;
  21494. }
  21495. else {
  21496. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21497. skyboxMaterial.backFaceCulling = false;
  21498. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21499. if (skyboxMaterial.reflectionTexture) {
  21500. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21501. }
  21502. skyboxMaterial.disableLighting = true;
  21503. hdrSkybox.infiniteDistance = true;
  21504. hdrSkybox.material = skyboxMaterial;
  21505. }
  21506. return hdrSkybox;
  21507. };
  21508. Scene.prototype.createDefaultEnvironment = function (options) {
  21509. if (BABYLON.EnvironmentHelper) {
  21510. return new BABYLON.EnvironmentHelper(options, this);
  21511. }
  21512. return null;
  21513. };
  21514. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21515. if (webVROptions === void 0) { webVROptions = {}; }
  21516. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21517. };
  21518. // Tags
  21519. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21520. if (tagsQuery === undefined) {
  21521. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21522. return list;
  21523. }
  21524. var listByTags = [];
  21525. forEach = forEach || (function (item) { return; });
  21526. for (var i in list) {
  21527. var item = list[i];
  21528. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21529. listByTags.push(item);
  21530. forEach(item);
  21531. }
  21532. }
  21533. return listByTags;
  21534. };
  21535. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21536. return this._getByTags(this.meshes, tagsQuery, forEach);
  21537. };
  21538. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21539. return this._getByTags(this.cameras, tagsQuery, forEach);
  21540. };
  21541. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21542. return this._getByTags(this.lights, tagsQuery, forEach);
  21543. };
  21544. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21545. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21546. };
  21547. /**
  21548. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21549. * This allowed control for front to back rendering or reversly depending of the special needs.
  21550. *
  21551. * @param renderingGroupId The rendering group id corresponding to its index
  21552. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21553. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21554. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21555. */
  21556. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21557. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21558. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21559. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21560. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21561. };
  21562. /**
  21563. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21564. *
  21565. * @param renderingGroupId The rendering group id corresponding to its index
  21566. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21567. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21568. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21569. */
  21570. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21571. if (depth === void 0) { depth = true; }
  21572. if (stencil === void 0) { stencil = true; }
  21573. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21574. };
  21575. /**
  21576. * Will flag all materials as dirty to trigger new shader compilation
  21577. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21578. */
  21579. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21580. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21581. var material = _a[_i];
  21582. if (predicate && !predicate(material)) {
  21583. continue;
  21584. }
  21585. material.markAsDirty(flag);
  21586. }
  21587. };
  21588. // Statics
  21589. Scene._FOGMODE_NONE = 0;
  21590. Scene._FOGMODE_EXP = 1;
  21591. Scene._FOGMODE_EXP2 = 2;
  21592. Scene._FOGMODE_LINEAR = 3;
  21593. Scene._uniqueIdCounter = 0;
  21594. Scene.MinDeltaTime = 1.0;
  21595. Scene.MaxDeltaTime = 1000.0;
  21596. /** The distance in pixel that you have to move to prevent some events */
  21597. Scene.DragMovementThreshold = 10; // in pixels
  21598. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21599. Scene.LongPressDelay = 500; // in milliseconds
  21600. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21601. Scene.DoubleClickDelay = 300; // in milliseconds
  21602. /** If you need to check double click without raising a single click at first click, enable this flag */
  21603. Scene.ExclusiveDoubleClickMode = false;
  21604. return Scene;
  21605. }());
  21606. BABYLON.Scene = Scene;
  21607. })(BABYLON || (BABYLON = {}));
  21608. //# sourceMappingURL=babylon.scene.js.map
  21609. var BABYLON;
  21610. (function (BABYLON) {
  21611. var Buffer = /** @class */ (function () {
  21612. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21613. if (instanced === void 0) { instanced = false; }
  21614. if (engine instanceof BABYLON.Mesh) {
  21615. this._engine = engine.getScene().getEngine();
  21616. }
  21617. else {
  21618. this._engine = engine;
  21619. }
  21620. this._updatable = updatable;
  21621. this._data = data;
  21622. this._strideSize = stride;
  21623. if (!postponeInternalCreation) {
  21624. this.create();
  21625. }
  21626. this._instanced = instanced;
  21627. this._instanceDivisor = instanced ? 1 : 0;
  21628. }
  21629. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21630. // a lot of these parameters are ignored as they are overriden by the buffer
  21631. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21632. };
  21633. // Properties
  21634. Buffer.prototype.isUpdatable = function () {
  21635. return this._updatable;
  21636. };
  21637. Buffer.prototype.getData = function () {
  21638. return this._data;
  21639. };
  21640. Buffer.prototype.getBuffer = function () {
  21641. return this._buffer;
  21642. };
  21643. Buffer.prototype.getStrideSize = function () {
  21644. return this._strideSize;
  21645. };
  21646. Buffer.prototype.getIsInstanced = function () {
  21647. return this._instanced;
  21648. };
  21649. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21650. get: function () {
  21651. return this._instanceDivisor;
  21652. },
  21653. set: function (value) {
  21654. this._instanceDivisor = value;
  21655. if (value == 0) {
  21656. this._instanced = false;
  21657. }
  21658. else {
  21659. this._instanced = true;
  21660. }
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. // Methods
  21666. Buffer.prototype.create = function (data) {
  21667. if (data === void 0) { data = null; }
  21668. if (!data && this._buffer) {
  21669. return; // nothing to do
  21670. }
  21671. data = data || this._data;
  21672. if (!data) {
  21673. return;
  21674. }
  21675. if (!this._buffer) {
  21676. if (this._updatable) {
  21677. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21678. this._data = data;
  21679. }
  21680. else {
  21681. this._buffer = this._engine.createVertexBuffer(data);
  21682. }
  21683. }
  21684. else if (this._updatable) {
  21685. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21686. this._data = data;
  21687. }
  21688. };
  21689. Buffer.prototype._rebuild = function () {
  21690. this._buffer = null;
  21691. this.create(this._data);
  21692. };
  21693. Buffer.prototype.update = function (data) {
  21694. this.create(data);
  21695. };
  21696. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21697. if (!this._buffer) {
  21698. return;
  21699. }
  21700. if (this._updatable) {
  21701. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21702. this._data = null;
  21703. }
  21704. };
  21705. Buffer.prototype.dispose = function () {
  21706. if (!this._buffer) {
  21707. return;
  21708. }
  21709. if (this._engine._releaseBuffer(this._buffer)) {
  21710. this._buffer = null;
  21711. }
  21712. };
  21713. return Buffer;
  21714. }());
  21715. BABYLON.Buffer = Buffer;
  21716. })(BABYLON || (BABYLON = {}));
  21717. //# sourceMappingURL=babylon.buffer.js.map
  21718. var BABYLON;
  21719. (function (BABYLON) {
  21720. var VertexBuffer = /** @class */ (function () {
  21721. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21722. if (!stride) {
  21723. // Deduce stride from kind
  21724. switch (kind) {
  21725. case VertexBuffer.PositionKind:
  21726. stride = 3;
  21727. break;
  21728. case VertexBuffer.NormalKind:
  21729. stride = 3;
  21730. break;
  21731. case VertexBuffer.UVKind:
  21732. case VertexBuffer.UV2Kind:
  21733. case VertexBuffer.UV3Kind:
  21734. case VertexBuffer.UV4Kind:
  21735. case VertexBuffer.UV5Kind:
  21736. case VertexBuffer.UV6Kind:
  21737. stride = 2;
  21738. break;
  21739. case VertexBuffer.TangentKind:
  21740. case VertexBuffer.ColorKind:
  21741. stride = 4;
  21742. break;
  21743. case VertexBuffer.MatricesIndicesKind:
  21744. case VertexBuffer.MatricesIndicesExtraKind:
  21745. stride = 4;
  21746. break;
  21747. case VertexBuffer.MatricesWeightsKind:
  21748. case VertexBuffer.MatricesWeightsExtraKind:
  21749. default:
  21750. stride = 4;
  21751. break;
  21752. }
  21753. }
  21754. if (data instanceof BABYLON.Buffer) {
  21755. if (!stride) {
  21756. stride = data.getStrideSize();
  21757. }
  21758. this._buffer = data;
  21759. this._ownsBuffer = false;
  21760. }
  21761. else {
  21762. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21763. this._ownsBuffer = true;
  21764. }
  21765. this._stride = stride;
  21766. this._offset = offset ? offset : 0;
  21767. this._size = size ? size : stride;
  21768. this._kind = kind;
  21769. }
  21770. VertexBuffer.prototype._rebuild = function () {
  21771. if (!this._buffer) {
  21772. return;
  21773. }
  21774. this._buffer._rebuild();
  21775. };
  21776. /**
  21777. * Returns the kind of the VertexBuffer (string).
  21778. */
  21779. VertexBuffer.prototype.getKind = function () {
  21780. return this._kind;
  21781. };
  21782. // Properties
  21783. /**
  21784. * Boolean : is the VertexBuffer updatable ?
  21785. */
  21786. VertexBuffer.prototype.isUpdatable = function () {
  21787. return this._buffer.isUpdatable();
  21788. };
  21789. /**
  21790. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21791. */
  21792. VertexBuffer.prototype.getData = function () {
  21793. return this._buffer.getData();
  21794. };
  21795. /**
  21796. * Returns the WebGLBuffer associated to the VertexBuffer.
  21797. */
  21798. VertexBuffer.prototype.getBuffer = function () {
  21799. return this._buffer.getBuffer();
  21800. };
  21801. /**
  21802. * Returns the stride of the VertexBuffer (integer).
  21803. */
  21804. VertexBuffer.prototype.getStrideSize = function () {
  21805. return this._stride;
  21806. };
  21807. /**
  21808. * Returns the offset (integer).
  21809. */
  21810. VertexBuffer.prototype.getOffset = function () {
  21811. return this._offset;
  21812. };
  21813. /**
  21814. * Returns the VertexBuffer total size (integer).
  21815. */
  21816. VertexBuffer.prototype.getSize = function () {
  21817. return this._size;
  21818. };
  21819. /**
  21820. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21821. */
  21822. VertexBuffer.prototype.getIsInstanced = function () {
  21823. return this._buffer.getIsInstanced();
  21824. };
  21825. /**
  21826. * Returns the instancing divisor, zero for non-instanced (integer).
  21827. */
  21828. VertexBuffer.prototype.getInstanceDivisor = function () {
  21829. return this._buffer.instanceDivisor;
  21830. };
  21831. // Methods
  21832. /**
  21833. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21834. * Returns the created WebGLBuffer.
  21835. */
  21836. VertexBuffer.prototype.create = function (data) {
  21837. return this._buffer.create(data);
  21838. };
  21839. /**
  21840. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21841. * Returns the updated WebGLBuffer.
  21842. */
  21843. VertexBuffer.prototype.update = function (data) {
  21844. return this._buffer.update(data);
  21845. };
  21846. /**
  21847. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21848. * Returns the directly updated WebGLBuffer.
  21849. */
  21850. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21851. return this._buffer.updateDirectly(data, offset);
  21852. };
  21853. /**
  21854. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21855. */
  21856. VertexBuffer.prototype.dispose = function () {
  21857. if (this._ownsBuffer) {
  21858. this._buffer.dispose();
  21859. }
  21860. };
  21861. Object.defineProperty(VertexBuffer, "PositionKind", {
  21862. get: function () {
  21863. return VertexBuffer._PositionKind;
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(VertexBuffer, "NormalKind", {
  21869. get: function () {
  21870. return VertexBuffer._NormalKind;
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(VertexBuffer, "TangentKind", {
  21876. get: function () {
  21877. return VertexBuffer._TangentKind;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. Object.defineProperty(VertexBuffer, "UVKind", {
  21883. get: function () {
  21884. return VertexBuffer._UVKind;
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21890. get: function () {
  21891. return VertexBuffer._UV2Kind;
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21897. get: function () {
  21898. return VertexBuffer._UV3Kind;
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21904. get: function () {
  21905. return VertexBuffer._UV4Kind;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21911. get: function () {
  21912. return VertexBuffer._UV5Kind;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21918. get: function () {
  21919. return VertexBuffer._UV6Kind;
  21920. },
  21921. enumerable: true,
  21922. configurable: true
  21923. });
  21924. Object.defineProperty(VertexBuffer, "ColorKind", {
  21925. get: function () {
  21926. return VertexBuffer._ColorKind;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21932. get: function () {
  21933. return VertexBuffer._MatricesIndicesKind;
  21934. },
  21935. enumerable: true,
  21936. configurable: true
  21937. });
  21938. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21939. get: function () {
  21940. return VertexBuffer._MatricesWeightsKind;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21946. get: function () {
  21947. return VertexBuffer._MatricesIndicesExtraKind;
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21953. get: function () {
  21954. return VertexBuffer._MatricesWeightsExtraKind;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. // Enums
  21960. VertexBuffer._PositionKind = "position";
  21961. VertexBuffer._NormalKind = "normal";
  21962. VertexBuffer._TangentKind = "tangent";
  21963. VertexBuffer._UVKind = "uv";
  21964. VertexBuffer._UV2Kind = "uv2";
  21965. VertexBuffer._UV3Kind = "uv3";
  21966. VertexBuffer._UV4Kind = "uv4";
  21967. VertexBuffer._UV5Kind = "uv5";
  21968. VertexBuffer._UV6Kind = "uv6";
  21969. VertexBuffer._ColorKind = "color";
  21970. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21971. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21972. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21973. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21974. return VertexBuffer;
  21975. }());
  21976. BABYLON.VertexBuffer = VertexBuffer;
  21977. })(BABYLON || (BABYLON = {}));
  21978. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21979. var BABYLON;
  21980. (function (BABYLON) {
  21981. var InternalTexture = /** @class */ (function () {
  21982. function InternalTexture(engine, dataSource) {
  21983. this.onLoadedObservable = new BABYLON.Observable();
  21984. // Private
  21985. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21986. this._references = 1;
  21987. this._engine = engine;
  21988. this._dataSource = dataSource;
  21989. this._webGLTexture = engine._createTexture();
  21990. }
  21991. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21992. get: function () {
  21993. return this._dataSource;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. InternalTexture.prototype.incrementReferences = function () {
  21999. this._references++;
  22000. };
  22001. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22002. if (depth === void 0) { depth = 1; }
  22003. this.width = width;
  22004. this.height = height;
  22005. this.depth = depth;
  22006. this.baseWidth = width;
  22007. this.baseHeight = height;
  22008. this.baseDepth = depth;
  22009. this._size = width * height * depth;
  22010. };
  22011. InternalTexture.prototype._rebuild = function () {
  22012. var _this = this;
  22013. var proxy;
  22014. this.isReady = false;
  22015. this._cachedCoordinatesMode = null;
  22016. this._cachedWrapU = null;
  22017. this._cachedWrapV = null;
  22018. this._cachedAnisotropicFilteringLevel = null;
  22019. switch (this._dataSource) {
  22020. case InternalTexture.DATASOURCE_TEMP:
  22021. return;
  22022. case InternalTexture.DATASOURCE_URL:
  22023. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22024. _this.isReady = true;
  22025. }, null, this._buffer, undefined, this.format);
  22026. proxy._swapAndDie(this);
  22027. return;
  22028. case InternalTexture.DATASOURCE_RAW:
  22029. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22030. proxy._swapAndDie(this);
  22031. this.isReady = true;
  22032. return;
  22033. case InternalTexture.DATASOURCE_RAW3D:
  22034. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22035. proxy._swapAndDie(this);
  22036. this.isReady = true;
  22037. return;
  22038. case InternalTexture.DATASOURCE_DYNAMIC:
  22039. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22040. proxy._swapAndDie(this);
  22041. // The engine will make sure to update content so no need to flag it as isReady = true
  22042. return;
  22043. case InternalTexture.DATASOURCE_RENDERTARGET:
  22044. var options = new BABYLON.RenderTargetCreationOptions();
  22045. options.generateDepthBuffer = this._generateDepthBuffer;
  22046. options.generateMipMaps = this.generateMipMaps;
  22047. options.generateStencilBuffer = this._generateStencilBuffer;
  22048. options.samplingMode = this.samplingMode;
  22049. options.type = this.type;
  22050. if (this.isCube) {
  22051. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22052. }
  22053. else {
  22054. var size = {
  22055. width: this.width,
  22056. height: this.height
  22057. };
  22058. proxy = this._engine.createRenderTargetTexture(size, options);
  22059. }
  22060. proxy._swapAndDie(this);
  22061. this.isReady = true;
  22062. return;
  22063. case InternalTexture.DATASOURCE_CUBE:
  22064. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22065. _this.isReady = true;
  22066. }, null, this.format, this._extension);
  22067. proxy._swapAndDie(this);
  22068. return;
  22069. case InternalTexture.DATASOURCE_CUBERAW:
  22070. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22071. proxy._swapAndDie(this);
  22072. this.isReady = true;
  22073. return;
  22074. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22075. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22076. if (proxy) {
  22077. proxy._swapAndDie(_this);
  22078. }
  22079. _this.isReady = true;
  22080. }, null, this.format, this._extension);
  22081. return;
  22082. }
  22083. };
  22084. InternalTexture.prototype._swapAndDie = function (target) {
  22085. target._webGLTexture = this._webGLTexture;
  22086. if (this._framebuffer) {
  22087. target._framebuffer = this._framebuffer;
  22088. }
  22089. if (this._depthStencilBuffer) {
  22090. target._depthStencilBuffer = this._depthStencilBuffer;
  22091. }
  22092. if (this._lodTextureHigh) {
  22093. if (target._lodTextureHigh) {
  22094. target._lodTextureHigh.dispose();
  22095. }
  22096. target._lodTextureHigh = this._lodTextureHigh;
  22097. }
  22098. if (this._lodTextureMid) {
  22099. if (target._lodTextureMid) {
  22100. target._lodTextureMid.dispose();
  22101. }
  22102. target._lodTextureMid = this._lodTextureMid;
  22103. }
  22104. if (this._lodTextureLow) {
  22105. if (target._lodTextureLow) {
  22106. target._lodTextureLow.dispose();
  22107. }
  22108. target._lodTextureLow = this._lodTextureLow;
  22109. }
  22110. var cache = this._engine.getLoadedTexturesCache();
  22111. var index = cache.indexOf(this);
  22112. if (index !== -1) {
  22113. cache.splice(index, 1);
  22114. }
  22115. };
  22116. InternalTexture.prototype.dispose = function () {
  22117. if (!this._webGLTexture) {
  22118. return;
  22119. }
  22120. this._references--;
  22121. if (this._references === 0) {
  22122. this._engine._releaseTexture(this);
  22123. this._webGLTexture = null;
  22124. }
  22125. };
  22126. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22127. InternalTexture.DATASOURCE_URL = 1;
  22128. InternalTexture.DATASOURCE_TEMP = 2;
  22129. InternalTexture.DATASOURCE_RAW = 3;
  22130. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22131. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22132. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22133. InternalTexture.DATASOURCE_CUBE = 7;
  22134. InternalTexture.DATASOURCE_CUBERAW = 8;
  22135. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22136. InternalTexture.DATASOURCE_RAW3D = 10;
  22137. return InternalTexture;
  22138. }());
  22139. BABYLON.InternalTexture = InternalTexture;
  22140. })(BABYLON || (BABYLON = {}));
  22141. //# sourceMappingURL=babylon.internalTexture.js.map
  22142. var BABYLON;
  22143. (function (BABYLON) {
  22144. var BaseTexture = /** @class */ (function () {
  22145. function BaseTexture(scene) {
  22146. this._hasAlpha = false;
  22147. this.getAlphaFromRGB = false;
  22148. this.level = 1;
  22149. this.coordinatesIndex = 0;
  22150. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22151. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22152. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22153. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22154. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22155. this.isCube = false;
  22156. this.is3D = false;
  22157. this.gammaSpace = true;
  22158. this.invertZ = false;
  22159. this.lodLevelInAlpha = false;
  22160. this.lodGenerationOffset = 0.0;
  22161. this.lodGenerationScale = 0.8;
  22162. this.isRenderTarget = false;
  22163. this.animations = new Array();
  22164. /**
  22165. * An event triggered when the texture is disposed.
  22166. * @type {BABYLON.Observable}
  22167. */
  22168. this.onDisposeObservable = new BABYLON.Observable();
  22169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22170. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22171. if (this._scene) {
  22172. this._scene.textures.push(this);
  22173. }
  22174. this._uid = null;
  22175. }
  22176. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22177. get: function () {
  22178. return this._hasAlpha;
  22179. },
  22180. set: function (value) {
  22181. if (this._hasAlpha === value) {
  22182. return;
  22183. }
  22184. this._hasAlpha = value;
  22185. if (this._scene) {
  22186. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22187. }
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22193. get: function () {
  22194. return this._coordinatesMode;
  22195. },
  22196. set: function (value) {
  22197. if (this._coordinatesMode === value) {
  22198. return;
  22199. }
  22200. this._coordinatesMode = value;
  22201. if (this._scene) {
  22202. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22203. }
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(BaseTexture.prototype, "uid", {
  22209. get: function () {
  22210. if (!this._uid) {
  22211. this._uid = BABYLON.Tools.RandomId();
  22212. }
  22213. return this._uid;
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. BaseTexture.prototype.toString = function () {
  22219. return this.name;
  22220. };
  22221. BaseTexture.prototype.getClassName = function () {
  22222. return "BaseTexture";
  22223. };
  22224. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22225. set: function (callback) {
  22226. if (this._onDisposeObserver) {
  22227. this.onDisposeObservable.remove(this._onDisposeObserver);
  22228. }
  22229. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22235. get: function () {
  22236. return true;
  22237. },
  22238. enumerable: true,
  22239. configurable: true
  22240. });
  22241. BaseTexture.prototype.getScene = function () {
  22242. return this._scene;
  22243. };
  22244. BaseTexture.prototype.getTextureMatrix = function () {
  22245. return BABYLON.Matrix.IdentityReadOnly;
  22246. };
  22247. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22248. return BABYLON.Matrix.IdentityReadOnly;
  22249. };
  22250. BaseTexture.prototype.getInternalTexture = function () {
  22251. return this._texture;
  22252. };
  22253. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22254. return !this.isBlocking || this.isReady();
  22255. };
  22256. BaseTexture.prototype.isReady = function () {
  22257. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22258. this.delayLoad();
  22259. return false;
  22260. }
  22261. if (this._texture) {
  22262. return this._texture.isReady;
  22263. }
  22264. return false;
  22265. };
  22266. BaseTexture.prototype.getSize = function () {
  22267. if (this._texture && this._texture.width) {
  22268. return new BABYLON.Size(this._texture.width, this._texture.height);
  22269. }
  22270. if (this._texture && this._texture._size) {
  22271. return new BABYLON.Size(this._texture._size, this._texture._size);
  22272. }
  22273. return BABYLON.Size.Zero();
  22274. };
  22275. BaseTexture.prototype.getBaseSize = function () {
  22276. if (!this.isReady() || !this._texture)
  22277. return BABYLON.Size.Zero();
  22278. if (this._texture._size) {
  22279. return new BABYLON.Size(this._texture._size, this._texture._size);
  22280. }
  22281. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22282. };
  22283. BaseTexture.prototype.scale = function (ratio) {
  22284. };
  22285. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22286. get: function () {
  22287. return false;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22293. if (!this._scene) {
  22294. return null;
  22295. }
  22296. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22297. for (var index = 0; index < texturesCache.length; index++) {
  22298. var texturesCacheEntry = texturesCache[index];
  22299. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22300. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22301. texturesCacheEntry.incrementReferences();
  22302. return texturesCacheEntry;
  22303. }
  22304. }
  22305. }
  22306. return null;
  22307. };
  22308. BaseTexture.prototype._rebuild = function () {
  22309. };
  22310. BaseTexture.prototype.delayLoad = function () {
  22311. };
  22312. BaseTexture.prototype.clone = function () {
  22313. return null;
  22314. };
  22315. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22316. get: function () {
  22317. if (!this._texture) {
  22318. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22319. }
  22320. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22326. get: function () {
  22327. if (!this._texture) {
  22328. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22329. }
  22330. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22331. },
  22332. enumerable: true,
  22333. configurable: true
  22334. });
  22335. BaseTexture.prototype.readPixels = function (faceIndex) {
  22336. if (faceIndex === void 0) { faceIndex = 0; }
  22337. if (!this._texture) {
  22338. return null;
  22339. }
  22340. var size = this.getSize();
  22341. var scene = this.getScene();
  22342. if (!scene) {
  22343. return null;
  22344. }
  22345. var engine = scene.getEngine();
  22346. if (this._texture.isCube) {
  22347. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22348. }
  22349. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22350. };
  22351. BaseTexture.prototype.releaseInternalTexture = function () {
  22352. if (this._texture) {
  22353. this._texture.dispose();
  22354. this._texture = null;
  22355. }
  22356. };
  22357. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22358. get: function () {
  22359. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22360. return null;
  22361. }
  22362. if (!this._texture._sphericalPolynomial) {
  22363. this._texture._sphericalPolynomial =
  22364. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22365. }
  22366. return this._texture._sphericalPolynomial;
  22367. },
  22368. set: function (value) {
  22369. if (this._texture) {
  22370. this._texture._sphericalPolynomial = value;
  22371. }
  22372. },
  22373. enumerable: true,
  22374. configurable: true
  22375. });
  22376. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22377. get: function () {
  22378. if (this._texture) {
  22379. return this._texture._lodTextureHigh;
  22380. }
  22381. return null;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22387. get: function () {
  22388. if (this._texture) {
  22389. return this._texture._lodTextureMid;
  22390. }
  22391. return null;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22397. get: function () {
  22398. if (this._texture) {
  22399. return this._texture._lodTextureLow;
  22400. }
  22401. return null;
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. BaseTexture.prototype.dispose = function () {
  22407. if (!this._scene) {
  22408. return;
  22409. }
  22410. // Animations
  22411. this._scene.stopAnimation(this);
  22412. // Remove from scene
  22413. this._scene._removePendingData(this);
  22414. var index = this._scene.textures.indexOf(this);
  22415. if (index >= 0) {
  22416. this._scene.textures.splice(index, 1);
  22417. }
  22418. if (this._texture === undefined) {
  22419. return;
  22420. }
  22421. // Release
  22422. this.releaseInternalTexture();
  22423. // Callback
  22424. this.onDisposeObservable.notifyObservers(this);
  22425. this.onDisposeObservable.clear();
  22426. };
  22427. BaseTexture.prototype.serialize = function () {
  22428. if (!this.name) {
  22429. return null;
  22430. }
  22431. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22432. // Animations
  22433. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22434. return serializationObject;
  22435. };
  22436. BaseTexture.WhenAllReady = function (textures, callback) {
  22437. var numRemaining = textures.length;
  22438. if (numRemaining === 0) {
  22439. callback();
  22440. return;
  22441. }
  22442. var _loop_1 = function () {
  22443. texture = textures[i];
  22444. if (texture.isReady()) {
  22445. if (--numRemaining === 0) {
  22446. callback();
  22447. }
  22448. }
  22449. else {
  22450. onLoadObservable = texture.onLoadObservable;
  22451. var onLoadCallback_1 = function () {
  22452. onLoadObservable.removeCallback(onLoadCallback_1);
  22453. if (--numRemaining === 0) {
  22454. callback();
  22455. }
  22456. };
  22457. onLoadObservable.add(onLoadCallback_1);
  22458. }
  22459. };
  22460. var texture, onLoadObservable;
  22461. for (var i = 0; i < textures.length; i++) {
  22462. _loop_1();
  22463. }
  22464. };
  22465. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22466. __decorate([
  22467. BABYLON.serialize()
  22468. ], BaseTexture.prototype, "name", void 0);
  22469. __decorate([
  22470. BABYLON.serialize("hasAlpha")
  22471. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22472. __decorate([
  22473. BABYLON.serialize()
  22474. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22475. __decorate([
  22476. BABYLON.serialize()
  22477. ], BaseTexture.prototype, "level", void 0);
  22478. __decorate([
  22479. BABYLON.serialize()
  22480. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22481. __decorate([
  22482. BABYLON.serialize("coordinatesMode")
  22483. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22484. __decorate([
  22485. BABYLON.serialize()
  22486. ], BaseTexture.prototype, "wrapU", void 0);
  22487. __decorate([
  22488. BABYLON.serialize()
  22489. ], BaseTexture.prototype, "wrapV", void 0);
  22490. __decorate([
  22491. BABYLON.serialize()
  22492. ], BaseTexture.prototype, "wrapR", void 0);
  22493. __decorate([
  22494. BABYLON.serialize()
  22495. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22496. __decorate([
  22497. BABYLON.serialize()
  22498. ], BaseTexture.prototype, "isCube", void 0);
  22499. __decorate([
  22500. BABYLON.serialize()
  22501. ], BaseTexture.prototype, "is3D", void 0);
  22502. __decorate([
  22503. BABYLON.serialize()
  22504. ], BaseTexture.prototype, "gammaSpace", void 0);
  22505. __decorate([
  22506. BABYLON.serialize()
  22507. ], BaseTexture.prototype, "invertZ", void 0);
  22508. __decorate([
  22509. BABYLON.serialize()
  22510. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22511. __decorate([
  22512. BABYLON.serialize()
  22513. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22514. __decorate([
  22515. BABYLON.serialize()
  22516. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22517. __decorate([
  22518. BABYLON.serialize()
  22519. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22520. return BaseTexture;
  22521. }());
  22522. BABYLON.BaseTexture = BaseTexture;
  22523. })(BABYLON || (BABYLON = {}));
  22524. //# sourceMappingURL=babylon.baseTexture.js.map
  22525. var BABYLON;
  22526. (function (BABYLON) {
  22527. var Texture = /** @class */ (function (_super) {
  22528. __extends(Texture, _super);
  22529. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22530. if (noMipmap === void 0) { noMipmap = false; }
  22531. if (invertY === void 0) { invertY = true; }
  22532. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22533. if (onLoad === void 0) { onLoad = null; }
  22534. if (onError === void 0) { onError = null; }
  22535. if (buffer === void 0) { buffer = null; }
  22536. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22537. var _this = _super.call(this, scene) || this;
  22538. _this.uOffset = 0;
  22539. _this.vOffset = 0;
  22540. _this.uScale = 1.0;
  22541. _this.vScale = 1.0;
  22542. _this.uAng = 0;
  22543. _this.vAng = 0;
  22544. _this.wAng = 0;
  22545. _this._isBlocking = true;
  22546. _this.name = url || "";
  22547. _this.url = url;
  22548. _this._noMipmap = noMipmap;
  22549. _this._invertY = invertY;
  22550. _this._samplingMode = samplingMode;
  22551. _this._buffer = buffer;
  22552. _this._deleteBuffer = deleteBuffer;
  22553. if (format) {
  22554. _this._format = format;
  22555. }
  22556. scene = _this.getScene();
  22557. if (!scene) {
  22558. return _this;
  22559. }
  22560. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22561. var load = function () {
  22562. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22563. _this.onLoadObservable.notifyObservers(_this);
  22564. }
  22565. if (onLoad) {
  22566. onLoad();
  22567. }
  22568. if (!_this.isBlocking && scene) {
  22569. scene.resetCachedMaterial();
  22570. }
  22571. };
  22572. if (!_this.url) {
  22573. _this._delayedOnLoad = load;
  22574. _this._delayedOnError = onError;
  22575. return _this;
  22576. }
  22577. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22578. if (!_this._texture) {
  22579. if (!scene.useDelayedTextureLoading) {
  22580. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22581. if (deleteBuffer) {
  22582. delete _this._buffer;
  22583. }
  22584. }
  22585. else {
  22586. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22587. _this._delayedOnLoad = load;
  22588. _this._delayedOnError = onError;
  22589. }
  22590. }
  22591. else {
  22592. if (_this._texture.isReady) {
  22593. BABYLON.Tools.SetImmediate(function () { return load(); });
  22594. }
  22595. else {
  22596. _this._texture.onLoadedObservable.add(load);
  22597. }
  22598. }
  22599. return _this;
  22600. }
  22601. Object.defineProperty(Texture.prototype, "noMipmap", {
  22602. get: function () {
  22603. return this._noMipmap;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. Object.defineProperty(Texture.prototype, "isBlocking", {
  22609. get: function () {
  22610. return this._isBlocking;
  22611. },
  22612. set: function (value) {
  22613. this._isBlocking = value;
  22614. },
  22615. enumerable: true,
  22616. configurable: true
  22617. });
  22618. Object.defineProperty(Texture.prototype, "samplingMode", {
  22619. get: function () {
  22620. return this._samplingMode;
  22621. },
  22622. enumerable: true,
  22623. configurable: true
  22624. });
  22625. Texture.prototype.updateURL = function (url) {
  22626. this.url = url;
  22627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22628. this.delayLoad();
  22629. };
  22630. Texture.prototype.delayLoad = function () {
  22631. var _this = this;
  22632. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22633. return;
  22634. }
  22635. var scene = this.getScene();
  22636. if (!scene) {
  22637. return;
  22638. }
  22639. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22640. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22641. if (!this._texture) {
  22642. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22643. if (this._deleteBuffer) {
  22644. delete this._buffer;
  22645. }
  22646. }
  22647. else {
  22648. if (this._texture.isReady) {
  22649. BABYLON.Tools.SetImmediate(function () {
  22650. if (!_this._delayedOnLoad) {
  22651. return;
  22652. }
  22653. _this._delayedOnLoad();
  22654. });
  22655. }
  22656. else {
  22657. if (this._delayedOnLoad) {
  22658. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22659. }
  22660. }
  22661. }
  22662. };
  22663. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22664. if (!this._texture) {
  22665. return;
  22666. }
  22667. var scene = this.getScene();
  22668. if (!scene) {
  22669. return;
  22670. }
  22671. this._samplingMode = samplingMode;
  22672. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22673. };
  22674. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22675. x *= this.uScale;
  22676. y *= this.vScale;
  22677. x -= 0.5 * this.uScale;
  22678. y -= 0.5 * this.vScale;
  22679. z -= 0.5;
  22680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22681. t.x += 0.5 * this.uScale + this.uOffset;
  22682. t.y += 0.5 * this.vScale + this.vOffset;
  22683. t.z += 0.5;
  22684. };
  22685. Texture.prototype.getTextureMatrix = function () {
  22686. var _this = this;
  22687. if (this.uOffset === this._cachedUOffset &&
  22688. this.vOffset === this._cachedVOffset &&
  22689. this.uScale === this._cachedUScale &&
  22690. this.vScale === this._cachedVScale &&
  22691. this.uAng === this._cachedUAng &&
  22692. this.vAng === this._cachedVAng &&
  22693. this.wAng === this._cachedWAng) {
  22694. return this._cachedTextureMatrix;
  22695. }
  22696. this._cachedUOffset = this.uOffset;
  22697. this._cachedVOffset = this.vOffset;
  22698. this._cachedUScale = this.uScale;
  22699. this._cachedVScale = this.vScale;
  22700. this._cachedUAng = this.uAng;
  22701. this._cachedVAng = this.vAng;
  22702. this._cachedWAng = this.wAng;
  22703. if (!this._cachedTextureMatrix) {
  22704. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22705. this._rowGenerationMatrix = new BABYLON.Matrix();
  22706. this._t0 = BABYLON.Vector3.Zero();
  22707. this._t1 = BABYLON.Vector3.Zero();
  22708. this._t2 = BABYLON.Vector3.Zero();
  22709. }
  22710. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22711. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22712. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22713. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22714. this._t1.subtractInPlace(this._t0);
  22715. this._t2.subtractInPlace(this._t0);
  22716. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22717. this._cachedTextureMatrix.m[0] = this._t1.x;
  22718. this._cachedTextureMatrix.m[1] = this._t1.y;
  22719. this._cachedTextureMatrix.m[2] = this._t1.z;
  22720. this._cachedTextureMatrix.m[4] = this._t2.x;
  22721. this._cachedTextureMatrix.m[5] = this._t2.y;
  22722. this._cachedTextureMatrix.m[6] = this._t2.z;
  22723. this._cachedTextureMatrix.m[8] = this._t0.x;
  22724. this._cachedTextureMatrix.m[9] = this._t0.y;
  22725. this._cachedTextureMatrix.m[10] = this._t0.z;
  22726. var scene = this.getScene();
  22727. if (!scene) {
  22728. return this._cachedTextureMatrix;
  22729. }
  22730. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22731. return mat.hasTexture(_this);
  22732. });
  22733. return this._cachedTextureMatrix;
  22734. };
  22735. Texture.prototype.getReflectionTextureMatrix = function () {
  22736. var _this = this;
  22737. var scene = this.getScene();
  22738. if (!scene) {
  22739. return this._cachedTextureMatrix;
  22740. }
  22741. if (this.uOffset === this._cachedUOffset &&
  22742. this.vOffset === this._cachedVOffset &&
  22743. this.uScale === this._cachedUScale &&
  22744. this.vScale === this._cachedVScale &&
  22745. this.coordinatesMode === this._cachedCoordinatesMode) {
  22746. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22747. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22748. return this._cachedTextureMatrix;
  22749. }
  22750. }
  22751. else {
  22752. return this._cachedTextureMatrix;
  22753. }
  22754. }
  22755. if (!this._cachedTextureMatrix) {
  22756. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22757. }
  22758. if (!this._projectionModeMatrix) {
  22759. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22760. }
  22761. this._cachedUOffset = this.uOffset;
  22762. this._cachedVOffset = this.vOffset;
  22763. this._cachedUScale = this.uScale;
  22764. this._cachedVScale = this.vScale;
  22765. this._cachedCoordinatesMode = this.coordinatesMode;
  22766. switch (this.coordinatesMode) {
  22767. case Texture.PLANAR_MODE:
  22768. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22769. this._cachedTextureMatrix[0] = this.uScale;
  22770. this._cachedTextureMatrix[5] = this.vScale;
  22771. this._cachedTextureMatrix[12] = this.uOffset;
  22772. this._cachedTextureMatrix[13] = this.vOffset;
  22773. break;
  22774. case Texture.PROJECTION_MODE:
  22775. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22776. this._projectionModeMatrix.m[0] = 0.5;
  22777. this._projectionModeMatrix.m[5] = -0.5;
  22778. this._projectionModeMatrix.m[10] = 0.0;
  22779. this._projectionModeMatrix.m[12] = 0.5;
  22780. this._projectionModeMatrix.m[13] = 0.5;
  22781. this._projectionModeMatrix.m[14] = 1.0;
  22782. this._projectionModeMatrix.m[15] = 1.0;
  22783. var projectionMatrix = scene.getProjectionMatrix();
  22784. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22785. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22786. break;
  22787. default:
  22788. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22789. break;
  22790. }
  22791. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22792. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22793. });
  22794. return this._cachedTextureMatrix;
  22795. };
  22796. Texture.prototype.clone = function () {
  22797. var _this = this;
  22798. return BABYLON.SerializationHelper.Clone(function () {
  22799. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22800. }, this);
  22801. };
  22802. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22803. get: function () {
  22804. if (!this._onLoadObservable) {
  22805. this._onLoadObservable = new BABYLON.Observable();
  22806. }
  22807. return this._onLoadObservable;
  22808. },
  22809. enumerable: true,
  22810. configurable: true
  22811. });
  22812. Texture.prototype.serialize = function () {
  22813. var serializationObject = _super.prototype.serialize.call(this);
  22814. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22815. serializationObject.base64String = this._buffer;
  22816. serializationObject.name = serializationObject.name.replace("data:", "");
  22817. }
  22818. return serializationObject;
  22819. };
  22820. Texture.prototype.getClassName = function () {
  22821. return "Texture";
  22822. };
  22823. Texture.prototype.dispose = function () {
  22824. _super.prototype.dispose.call(this);
  22825. if (this.onLoadObservable) {
  22826. this.onLoadObservable.clear();
  22827. this._onLoadObservable = null;
  22828. }
  22829. this._delayedOnLoad = null;
  22830. this._delayedOnError = null;
  22831. };
  22832. // Statics
  22833. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22834. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22835. if (onLoad === void 0) { onLoad = null; }
  22836. if (onError === void 0) { onError = null; }
  22837. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22838. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22839. };
  22840. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22841. if (parsedTexture.customType) {
  22842. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22843. // Update Sampling Mode
  22844. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22845. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22846. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22847. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22848. }
  22849. }
  22850. return parsedCustomTexture;
  22851. }
  22852. if (parsedTexture.isCube) {
  22853. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22854. }
  22855. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22856. return null;
  22857. }
  22858. var texture = BABYLON.SerializationHelper.Parse(function () {
  22859. var generateMipMaps = true;
  22860. if (parsedTexture.noMipmap) {
  22861. generateMipMaps = false;
  22862. }
  22863. if (parsedTexture.mirrorPlane) {
  22864. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22865. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22866. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22867. return mirrorTexture;
  22868. }
  22869. else if (parsedTexture.isRenderTarget) {
  22870. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22871. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22872. return renderTargetTexture;
  22873. }
  22874. else {
  22875. var texture;
  22876. if (parsedTexture.base64String) {
  22877. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  22878. }
  22879. else {
  22880. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  22881. }
  22882. return texture;
  22883. }
  22884. }, parsedTexture, scene);
  22885. // Update Sampling Mode
  22886. if (parsedTexture.samplingMode) {
  22887. var sampling = parsedTexture.samplingMode;
  22888. if (texture._samplingMode !== sampling) {
  22889. texture.updateSamplingMode(sampling);
  22890. }
  22891. }
  22892. // Animations
  22893. if (parsedTexture.animations) {
  22894. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22895. var parsedAnimation = parsedTexture.animations[animationIndex];
  22896. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22897. }
  22898. }
  22899. return texture;
  22900. };
  22901. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22902. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22903. if (noMipmap === void 0) { noMipmap = false; }
  22904. if (invertY === void 0) { invertY = true; }
  22905. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22906. if (onLoad === void 0) { onLoad = null; }
  22907. if (onError === void 0) { onError = null; }
  22908. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22909. if (name.substr(0, 5) !== "data:") {
  22910. name = "data:" + name;
  22911. }
  22912. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22913. };
  22914. // Constants
  22915. Texture.NEAREST_SAMPLINGMODE = 1;
  22916. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22917. Texture.BILINEAR_SAMPLINGMODE = 2;
  22918. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22919. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22920. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22921. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22922. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22923. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22924. Texture.NEAREST_LINEAR = 7;
  22925. Texture.NEAREST_NEAREST = 8;
  22926. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22927. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22928. Texture.LINEAR_LINEAR = 11;
  22929. Texture.LINEAR_NEAREST = 12;
  22930. Texture.EXPLICIT_MODE = 0;
  22931. Texture.SPHERICAL_MODE = 1;
  22932. Texture.PLANAR_MODE = 2;
  22933. Texture.CUBIC_MODE = 3;
  22934. Texture.PROJECTION_MODE = 4;
  22935. Texture.SKYBOX_MODE = 5;
  22936. Texture.INVCUBIC_MODE = 6;
  22937. Texture.EQUIRECTANGULAR_MODE = 7;
  22938. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22939. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22940. Texture.CLAMP_ADDRESSMODE = 0;
  22941. Texture.WRAP_ADDRESSMODE = 1;
  22942. Texture.MIRROR_ADDRESSMODE = 2;
  22943. __decorate([
  22944. BABYLON.serialize()
  22945. ], Texture.prototype, "url", void 0);
  22946. __decorate([
  22947. BABYLON.serialize()
  22948. ], Texture.prototype, "uOffset", void 0);
  22949. __decorate([
  22950. BABYLON.serialize()
  22951. ], Texture.prototype, "vOffset", void 0);
  22952. __decorate([
  22953. BABYLON.serialize()
  22954. ], Texture.prototype, "uScale", void 0);
  22955. __decorate([
  22956. BABYLON.serialize()
  22957. ], Texture.prototype, "vScale", void 0);
  22958. __decorate([
  22959. BABYLON.serialize()
  22960. ], Texture.prototype, "uAng", void 0);
  22961. __decorate([
  22962. BABYLON.serialize()
  22963. ], Texture.prototype, "vAng", void 0);
  22964. __decorate([
  22965. BABYLON.serialize()
  22966. ], Texture.prototype, "wAng", void 0);
  22967. __decorate([
  22968. BABYLON.serialize()
  22969. ], Texture.prototype, "isBlocking", null);
  22970. return Texture;
  22971. }(BABYLON.BaseTexture));
  22972. BABYLON.Texture = Texture;
  22973. })(BABYLON || (BABYLON = {}));
  22974. //# sourceMappingURL=babylon.texture.js.map
  22975. var BABYLON;
  22976. (function (BABYLON) {
  22977. var _InstancesBatch = /** @class */ (function () {
  22978. function _InstancesBatch() {
  22979. this.mustReturn = false;
  22980. this.visibleInstances = new Array();
  22981. this.renderSelf = new Array();
  22982. }
  22983. return _InstancesBatch;
  22984. }());
  22985. BABYLON._InstancesBatch = _InstancesBatch;
  22986. var Mesh = /** @class */ (function (_super) {
  22987. __extends(Mesh, _super);
  22988. /**
  22989. * @constructor
  22990. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22991. * @param {Scene} scene The scene to add this mesh to.
  22992. * @param {Node} parent The parent of this mesh, if it has one
  22993. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22994. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22995. * When false, achieved by calling a clone(), also passing False.
  22996. * This will make creation of children, recursive.
  22997. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22998. */
  22999. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23000. if (scene === void 0) { scene = null; }
  23001. if (parent === void 0) { parent = null; }
  23002. if (source === void 0) { source = null; }
  23003. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23004. var _this = _super.call(this, name, scene) || this;
  23005. // Events
  23006. /**
  23007. * An event triggered before rendering the mesh
  23008. * @type {BABYLON.Observable}
  23009. */
  23010. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23011. /**
  23012. * An event triggered after rendering the mesh
  23013. * @type {BABYLON.Observable}
  23014. */
  23015. _this.onAfterRenderObservable = new BABYLON.Observable();
  23016. /**
  23017. * An event triggered before drawing the mesh
  23018. * @type {BABYLON.Observable}
  23019. */
  23020. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23021. // Members
  23022. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23023. _this.instances = new Array();
  23024. _this._LODLevels = new Array();
  23025. _this._visibleInstances = {};
  23026. _this._renderIdForInstances = new Array();
  23027. _this._batchCache = new _InstancesBatch();
  23028. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23029. // Use by builder only to know what orientation were the mesh build in.
  23030. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23031. _this.overrideMaterialSideOrientation = null;
  23032. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23033. // Will be used to save a source mesh reference, If any
  23034. _this._source = null;
  23035. scene = _this.getScene();
  23036. if (source) {
  23037. // Source mesh
  23038. _this._source = source;
  23039. // Geometry
  23040. if (source._geometry) {
  23041. source._geometry.applyToMesh(_this);
  23042. }
  23043. // Deep copy
  23044. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23045. // Tags
  23046. if (BABYLON.Tags.HasTags(source)) {
  23047. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23048. }
  23049. _this.metadata = source.metadata;
  23050. // Parent
  23051. _this.parent = source.parent;
  23052. // Pivot
  23053. _this.setPivotMatrix(source.getPivotMatrix());
  23054. _this.id = name + "." + source.id;
  23055. // Material
  23056. _this.material = source.material;
  23057. var index;
  23058. if (!doNotCloneChildren) {
  23059. // Children
  23060. var directDescendants = source.getDescendants(true);
  23061. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23062. var child = directDescendants[index_1];
  23063. if (child.clone) {
  23064. child.clone(name + "." + child.name, _this);
  23065. }
  23066. }
  23067. }
  23068. // Physics clone
  23069. var physicsEngine = _this.getScene().getPhysicsEngine();
  23070. if (clonePhysicsImpostor && physicsEngine) {
  23071. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23072. if (impostor) {
  23073. _this.physicsImpostor = impostor.clone(_this);
  23074. }
  23075. }
  23076. // Particles
  23077. for (index = 0; index < scene.particleSystems.length; index++) {
  23078. var system = scene.particleSystems[index];
  23079. if (system.emitter === source) {
  23080. system.clone(system.name, _this);
  23081. }
  23082. }
  23083. _this.computeWorldMatrix(true);
  23084. }
  23085. // Parent
  23086. if (parent !== null) {
  23087. _this.parent = parent;
  23088. }
  23089. return _this;
  23090. }
  23091. Object.defineProperty(Mesh, "FRONTSIDE", {
  23092. /**
  23093. * Mesh side orientation : usually the external or front surface
  23094. */
  23095. get: function () {
  23096. return Mesh._FRONTSIDE;
  23097. },
  23098. enumerable: true,
  23099. configurable: true
  23100. });
  23101. Object.defineProperty(Mesh, "BACKSIDE", {
  23102. /**
  23103. * Mesh side orientation : usually the internal or back surface
  23104. */
  23105. get: function () {
  23106. return Mesh._BACKSIDE;
  23107. },
  23108. enumerable: true,
  23109. configurable: true
  23110. });
  23111. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23112. /**
  23113. * Mesh side orientation : both internal and external or front and back surfaces
  23114. */
  23115. get: function () {
  23116. return Mesh._DOUBLESIDE;
  23117. },
  23118. enumerable: true,
  23119. configurable: true
  23120. });
  23121. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23122. /**
  23123. * Mesh side orientation : by default, `FRONTSIDE`
  23124. */
  23125. get: function () {
  23126. return Mesh._DEFAULTSIDE;
  23127. },
  23128. enumerable: true,
  23129. configurable: true
  23130. });
  23131. Object.defineProperty(Mesh, "NO_CAP", {
  23132. /**
  23133. * Mesh cap setting : no cap
  23134. */
  23135. get: function () {
  23136. return Mesh._NO_CAP;
  23137. },
  23138. enumerable: true,
  23139. configurable: true
  23140. });
  23141. Object.defineProperty(Mesh, "CAP_START", {
  23142. /**
  23143. * Mesh cap setting : one cap at the beginning of the mesh
  23144. */
  23145. get: function () {
  23146. return Mesh._CAP_START;
  23147. },
  23148. enumerable: true,
  23149. configurable: true
  23150. });
  23151. Object.defineProperty(Mesh, "CAP_END", {
  23152. /**
  23153. * Mesh cap setting : one cap at the end of the mesh
  23154. */
  23155. get: function () {
  23156. return Mesh._CAP_END;
  23157. },
  23158. enumerable: true,
  23159. configurable: true
  23160. });
  23161. Object.defineProperty(Mesh, "CAP_ALL", {
  23162. /**
  23163. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23164. */
  23165. get: function () {
  23166. return Mesh._CAP_ALL;
  23167. },
  23168. enumerable: true,
  23169. configurable: true
  23170. });
  23171. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23172. set: function (callback) {
  23173. if (this._onBeforeDrawObserver) {
  23174. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23175. }
  23176. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23177. },
  23178. enumerable: true,
  23179. configurable: true
  23180. });
  23181. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23182. get: function () {
  23183. return this._morphTargetManager;
  23184. },
  23185. set: function (value) {
  23186. if (this._morphTargetManager === value) {
  23187. return;
  23188. }
  23189. this._morphTargetManager = value;
  23190. this._syncGeometryWithMorphTargetManager();
  23191. },
  23192. enumerable: true,
  23193. configurable: true
  23194. });
  23195. Object.defineProperty(Mesh.prototype, "source", {
  23196. get: function () {
  23197. return this._source;
  23198. },
  23199. enumerable: true,
  23200. configurable: true
  23201. });
  23202. // Methods
  23203. /**
  23204. * Returns the string "Mesh".
  23205. */
  23206. Mesh.prototype.getClassName = function () {
  23207. return "Mesh";
  23208. };
  23209. /**
  23210. * Returns a string.
  23211. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23212. */
  23213. Mesh.prototype.toString = function (fullDetails) {
  23214. var ret = _super.prototype.toString.call(this, fullDetails);
  23215. ret += ", n vertices: " + this.getTotalVertices();
  23216. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23217. if (this.animations) {
  23218. for (var i = 0; i < this.animations.length; i++) {
  23219. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23220. }
  23221. }
  23222. if (fullDetails) {
  23223. if (this._geometry) {
  23224. var ib = this.getIndices();
  23225. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23226. if (vb && ib) {
  23227. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23228. }
  23229. }
  23230. else {
  23231. ret += ", flat shading: UNKNOWN";
  23232. }
  23233. }
  23234. return ret;
  23235. };
  23236. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23237. /**
  23238. * True if the mesh has some Levels Of Details (LOD).
  23239. * Returns a boolean.
  23240. */
  23241. get: function () {
  23242. return this._LODLevels.length > 0;
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. Mesh.prototype._sortLODLevels = function () {
  23248. this._LODLevels.sort(function (a, b) {
  23249. if (a.distance < b.distance) {
  23250. return 1;
  23251. }
  23252. if (a.distance > b.distance) {
  23253. return -1;
  23254. }
  23255. return 0;
  23256. });
  23257. };
  23258. /**
  23259. * Add a mesh as LOD level triggered at the given distance.
  23260. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23261. * @param {number} distance The distance from the center of the object to show this level
  23262. * @param {Mesh} mesh The mesh to be added as LOD level
  23263. * @return {Mesh} This mesh (for chaining)
  23264. */
  23265. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23266. if (mesh && mesh._masterMesh) {
  23267. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23268. return this;
  23269. }
  23270. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23271. this._LODLevels.push(level);
  23272. if (mesh) {
  23273. mesh._masterMesh = this;
  23274. }
  23275. this._sortLODLevels();
  23276. return this;
  23277. };
  23278. /**
  23279. * Returns the LOD level mesh at the passed distance or null if not found.
  23280. * It is related to the method `addLODLevel(distance, mesh)`.
  23281. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23282. * Returns an object Mesh or `null`.
  23283. */
  23284. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23285. for (var index = 0; index < this._LODLevels.length; index++) {
  23286. var level = this._LODLevels[index];
  23287. if (level.distance === distance) {
  23288. return level.mesh;
  23289. }
  23290. }
  23291. return null;
  23292. };
  23293. /**
  23294. * Remove a mesh from the LOD array
  23295. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23296. * @param {Mesh} mesh The mesh to be removed.
  23297. * @return {Mesh} This mesh (for chaining)
  23298. */
  23299. Mesh.prototype.removeLODLevel = function (mesh) {
  23300. for (var index = 0; index < this._LODLevels.length; index++) {
  23301. if (this._LODLevels[index].mesh === mesh) {
  23302. this._LODLevels.splice(index, 1);
  23303. if (mesh) {
  23304. mesh._masterMesh = null;
  23305. }
  23306. }
  23307. }
  23308. this._sortLODLevels();
  23309. return this;
  23310. };
  23311. /**
  23312. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23313. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23314. */
  23315. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23316. if (!this._LODLevels || this._LODLevels.length === 0) {
  23317. return this;
  23318. }
  23319. var bSphere;
  23320. if (boundingSphere) {
  23321. bSphere = boundingSphere;
  23322. }
  23323. else {
  23324. var boundingInfo = this.getBoundingInfo();
  23325. bSphere = boundingInfo.boundingSphere;
  23326. }
  23327. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23328. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23329. if (this.onLODLevelSelection) {
  23330. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23331. }
  23332. return this;
  23333. }
  23334. for (var index = 0; index < this._LODLevels.length; index++) {
  23335. var level = this._LODLevels[index];
  23336. if (level.distance < distanceToCamera) {
  23337. if (level.mesh) {
  23338. level.mesh._preActivate();
  23339. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23340. }
  23341. if (this.onLODLevelSelection) {
  23342. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23343. }
  23344. return level.mesh;
  23345. }
  23346. }
  23347. if (this.onLODLevelSelection) {
  23348. this.onLODLevelSelection(distanceToCamera, this, this);
  23349. }
  23350. return this;
  23351. };
  23352. Object.defineProperty(Mesh.prototype, "geometry", {
  23353. /**
  23354. * Returns the mesh internal Geometry object.
  23355. */
  23356. get: function () {
  23357. return this._geometry;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. /**
  23363. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23364. */
  23365. Mesh.prototype.getTotalVertices = function () {
  23366. if (!this._geometry) {
  23367. return 0;
  23368. }
  23369. return this._geometry.getTotalVertices();
  23370. };
  23371. /**
  23372. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23373. * 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.
  23374. * You can force the copy with forceCopy === true
  23375. * Returns null if the mesh has no geometry or no vertex buffer.
  23376. * Possible `kind` values :
  23377. * - BABYLON.VertexBuffer.PositionKind
  23378. * - BABYLON.VertexBuffer.UVKind
  23379. * - BABYLON.VertexBuffer.UV2Kind
  23380. * - BABYLON.VertexBuffer.UV3Kind
  23381. * - BABYLON.VertexBuffer.UV4Kind
  23382. * - BABYLON.VertexBuffer.UV5Kind
  23383. * - BABYLON.VertexBuffer.UV6Kind
  23384. * - BABYLON.VertexBuffer.ColorKind
  23385. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23386. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23387. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23388. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23389. */
  23390. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23391. if (!this._geometry) {
  23392. return null;
  23393. }
  23394. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23395. };
  23396. /**
  23397. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23398. * Returns `null` if the mesh has no geometry.
  23399. * Possible `kind` values :
  23400. * - BABYLON.VertexBuffer.PositionKind
  23401. * - BABYLON.VertexBuffer.UVKind
  23402. * - BABYLON.VertexBuffer.UV2Kind
  23403. * - BABYLON.VertexBuffer.UV3Kind
  23404. * - BABYLON.VertexBuffer.UV4Kind
  23405. * - BABYLON.VertexBuffer.UV5Kind
  23406. * - BABYLON.VertexBuffer.UV6Kind
  23407. * - BABYLON.VertexBuffer.ColorKind
  23408. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23409. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23410. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23411. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23412. */
  23413. Mesh.prototype.getVertexBuffer = function (kind) {
  23414. if (!this._geometry) {
  23415. return null;
  23416. }
  23417. return this._geometry.getVertexBuffer(kind);
  23418. };
  23419. /**
  23420. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23421. * Possible `kind` values :
  23422. * - BABYLON.VertexBuffer.PositionKind
  23423. * - BABYLON.VertexBuffer.UVKind
  23424. * - BABYLON.VertexBuffer.UV2Kind
  23425. * - BABYLON.VertexBuffer.UV3Kind
  23426. * - BABYLON.VertexBuffer.UV4Kind
  23427. * - BABYLON.VertexBuffer.UV5Kind
  23428. * - BABYLON.VertexBuffer.UV6Kind
  23429. * - BABYLON.VertexBuffer.ColorKind
  23430. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23431. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23432. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23433. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23434. */
  23435. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23436. if (!this._geometry) {
  23437. if (this._delayInfo) {
  23438. return this._delayInfo.indexOf(kind) !== -1;
  23439. }
  23440. return false;
  23441. }
  23442. return this._geometry.isVerticesDataPresent(kind);
  23443. };
  23444. /**
  23445. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23446. * Possible `kind` values :
  23447. * - BABYLON.VertexBuffer.PositionKind
  23448. * - BABYLON.VertexBuffer.UVKind
  23449. * - BABYLON.VertexBuffer.UV2Kind
  23450. * - BABYLON.VertexBuffer.UV3Kind
  23451. * - BABYLON.VertexBuffer.UV4Kind
  23452. * - BABYLON.VertexBuffer.UV5Kind
  23453. * - BABYLON.VertexBuffer.UV6Kind
  23454. * - BABYLON.VertexBuffer.ColorKind
  23455. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23456. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23457. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23458. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23459. */
  23460. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23461. if (!this._geometry) {
  23462. if (this._delayInfo) {
  23463. return this._delayInfo.indexOf(kind) !== -1;
  23464. }
  23465. return false;
  23466. }
  23467. return this._geometry.isVertexBufferUpdatable(kind);
  23468. };
  23469. /**
  23470. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23471. * Possible `kind` values :
  23472. * - BABYLON.VertexBuffer.PositionKind
  23473. * - BABYLON.VertexBuffer.UVKind
  23474. * - BABYLON.VertexBuffer.UV2Kind
  23475. * - BABYLON.VertexBuffer.UV3Kind
  23476. * - BABYLON.VertexBuffer.UV4Kind
  23477. * - BABYLON.VertexBuffer.UV5Kind
  23478. * - BABYLON.VertexBuffer.UV6Kind
  23479. * - BABYLON.VertexBuffer.ColorKind
  23480. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23481. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23482. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23483. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23484. */
  23485. Mesh.prototype.getVerticesDataKinds = function () {
  23486. if (!this._geometry) {
  23487. var result = new Array();
  23488. if (this._delayInfo) {
  23489. this._delayInfo.forEach(function (kind, index, array) {
  23490. result.push(kind);
  23491. });
  23492. }
  23493. return result;
  23494. }
  23495. return this._geometry.getVerticesDataKinds();
  23496. };
  23497. /**
  23498. * Returns a positive integer : the total number of indices in this mesh geometry.
  23499. * Returns zero if the mesh has no geometry.
  23500. */
  23501. Mesh.prototype.getTotalIndices = function () {
  23502. if (!this._geometry) {
  23503. return 0;
  23504. }
  23505. return this._geometry.getTotalIndices();
  23506. };
  23507. /**
  23508. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23509. * 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.
  23510. * Returns an empty array if the mesh has no geometry.
  23511. */
  23512. Mesh.prototype.getIndices = function (copyWhenShared) {
  23513. if (!this._geometry) {
  23514. return [];
  23515. }
  23516. return this._geometry.getIndices(copyWhenShared);
  23517. };
  23518. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23519. get: function () {
  23520. return this._masterMesh !== null && this._masterMesh !== undefined;
  23521. },
  23522. enumerable: true,
  23523. configurable: true
  23524. });
  23525. /**
  23526. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23527. */
  23528. Mesh.prototype.isReady = function () {
  23529. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23530. return false;
  23531. }
  23532. return _super.prototype.isReady.call(this);
  23533. };
  23534. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23535. /**
  23536. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23537. * This property is pertinent only for updatable parametric shapes.
  23538. */
  23539. get: function () {
  23540. return this._areNormalsFrozen;
  23541. },
  23542. enumerable: true,
  23543. configurable: true
  23544. });
  23545. /**
  23546. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23547. * It has no effect at all on other shapes.
  23548. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23549. * Returns the Mesh.
  23550. */
  23551. Mesh.prototype.freezeNormals = function () {
  23552. this._areNormalsFrozen = true;
  23553. return this;
  23554. };
  23555. /**
  23556. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23557. * It has no effect at all on other shapes.
  23558. * It reactivates the mesh normals computation if it was previously frozen.
  23559. * Returns the Mesh.
  23560. */
  23561. Mesh.prototype.unfreezeNormals = function () {
  23562. this._areNormalsFrozen = false;
  23563. return this;
  23564. };
  23565. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23566. /**
  23567. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23568. */
  23569. set: function (count) {
  23570. this._overridenInstanceCount = count;
  23571. },
  23572. enumerable: true,
  23573. configurable: true
  23574. });
  23575. // Methods
  23576. Mesh.prototype._preActivate = function () {
  23577. var sceneRenderId = this.getScene().getRenderId();
  23578. if (this._preActivateId === sceneRenderId) {
  23579. return this;
  23580. }
  23581. this._preActivateId = sceneRenderId;
  23582. this._visibleInstances = null;
  23583. return this;
  23584. };
  23585. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23586. if (this._visibleInstances) {
  23587. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23588. }
  23589. return this;
  23590. };
  23591. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23592. if (!this._visibleInstances) {
  23593. this._visibleInstances = {};
  23594. this._visibleInstances.defaultRenderId = renderId;
  23595. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23596. }
  23597. if (!this._visibleInstances[renderId]) {
  23598. this._visibleInstances[renderId] = new Array();
  23599. }
  23600. this._visibleInstances[renderId].push(instance);
  23601. return this;
  23602. };
  23603. /**
  23604. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23605. * This means the mesh underlying bounding box and sphere are recomputed.
  23606. * Returns the Mesh.
  23607. */
  23608. Mesh.prototype.refreshBoundingInfo = function () {
  23609. return this._refreshBoundingInfo(false);
  23610. };
  23611. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23612. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23613. return this;
  23614. }
  23615. var data = this._getPositionData(applySkeleton);
  23616. if (data) {
  23617. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23618. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23619. }
  23620. if (this.subMeshes) {
  23621. for (var index = 0; index < this.subMeshes.length; index++) {
  23622. this.subMeshes[index].refreshBoundingInfo();
  23623. }
  23624. }
  23625. this._updateBoundingInfo();
  23626. return this;
  23627. };
  23628. Mesh.prototype._getPositionData = function (applySkeleton) {
  23629. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23630. if (data && applySkeleton && this.skeleton) {
  23631. data = data.slice();
  23632. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23633. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23634. if (matricesWeightsData && matricesIndicesData) {
  23635. var needExtras = this.numBoneInfluencers > 4;
  23636. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23637. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23638. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23639. var tempVector = BABYLON.Tmp.Vector3[0];
  23640. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23641. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23642. var matWeightIdx = 0;
  23643. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23644. finalMatrix.reset();
  23645. var inf;
  23646. var weight;
  23647. for (inf = 0; inf < 4; inf++) {
  23648. weight = matricesWeightsData[matWeightIdx + inf];
  23649. if (weight <= 0)
  23650. break;
  23651. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23652. finalMatrix.addToSelf(tempMatrix);
  23653. }
  23654. if (needExtras) {
  23655. for (inf = 0; inf < 4; inf++) {
  23656. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23657. if (weight <= 0)
  23658. break;
  23659. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23660. finalMatrix.addToSelf(tempMatrix);
  23661. }
  23662. }
  23663. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23664. tempVector.toArray(data, index);
  23665. }
  23666. }
  23667. }
  23668. return data;
  23669. };
  23670. Mesh.prototype._createGlobalSubMesh = function (force) {
  23671. var totalVertices = this.getTotalVertices();
  23672. if (!totalVertices || !this.getIndices()) {
  23673. return null;
  23674. }
  23675. // Check if we need to recreate the submeshes
  23676. if (this.subMeshes && this.subMeshes.length > 0) {
  23677. var ib = this.getIndices();
  23678. if (!ib) {
  23679. return null;
  23680. }
  23681. var totalIndices = ib.length;
  23682. var needToRecreate = false;
  23683. if (force) {
  23684. needToRecreate = true;
  23685. }
  23686. else {
  23687. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23688. var submesh = _a[_i];
  23689. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23690. needToRecreate = true;
  23691. break;
  23692. }
  23693. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23694. needToRecreate = true;
  23695. break;
  23696. }
  23697. }
  23698. }
  23699. if (!needToRecreate) {
  23700. return this.subMeshes[0];
  23701. }
  23702. }
  23703. this.releaseSubMeshes();
  23704. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23705. };
  23706. Mesh.prototype.subdivide = function (count) {
  23707. if (count < 1) {
  23708. return;
  23709. }
  23710. var totalIndices = this.getTotalIndices();
  23711. var subdivisionSize = (totalIndices / count) | 0;
  23712. var offset = 0;
  23713. // Ensure that subdivisionSize is a multiple of 3
  23714. while (subdivisionSize % 3 !== 0) {
  23715. subdivisionSize++;
  23716. }
  23717. this.releaseSubMeshes();
  23718. for (var index = 0; index < count; index++) {
  23719. if (offset >= totalIndices) {
  23720. break;
  23721. }
  23722. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23723. offset += subdivisionSize;
  23724. }
  23725. this.synchronizeInstances();
  23726. };
  23727. /**
  23728. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23729. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23730. * The `data` are either a numeric array either a Float32Array.
  23731. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23732. * 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).
  23733. * Note that a new underlying VertexBuffer object is created each call.
  23734. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23735. *
  23736. * Possible `kind` values :
  23737. * - BABYLON.VertexBuffer.PositionKind
  23738. * - BABYLON.VertexBuffer.UVKind
  23739. * - BABYLON.VertexBuffer.UV2Kind
  23740. * - BABYLON.VertexBuffer.UV3Kind
  23741. * - BABYLON.VertexBuffer.UV4Kind
  23742. * - BABYLON.VertexBuffer.UV5Kind
  23743. * - BABYLON.VertexBuffer.UV6Kind
  23744. * - BABYLON.VertexBuffer.ColorKind
  23745. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23746. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23747. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23748. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23749. *
  23750. * Returns the Mesh.
  23751. */
  23752. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23753. if (updatable === void 0) { updatable = false; }
  23754. if (!this._geometry) {
  23755. var vertexData = new BABYLON.VertexData();
  23756. vertexData.set(data, kind);
  23757. var scene = this.getScene();
  23758. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23759. }
  23760. else {
  23761. this._geometry.setVerticesData(kind, data, updatable, stride);
  23762. }
  23763. return this;
  23764. };
  23765. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23766. if (updatable === void 0) { updatable = true; }
  23767. var vb = this.getVertexBuffer(kind);
  23768. if (!vb || vb.isUpdatable() === updatable) {
  23769. return;
  23770. }
  23771. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23772. };
  23773. /**
  23774. * Sets the mesh VertexBuffer.
  23775. * Returns the Mesh.
  23776. */
  23777. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23778. if (!this._geometry) {
  23779. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23780. }
  23781. this._geometry.setVerticesBuffer(buffer);
  23782. return this;
  23783. };
  23784. /**
  23785. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23786. * If the mesh has no geometry, it is simply returned as it is.
  23787. * The `data` are either a numeric array either a Float32Array.
  23788. * No new underlying VertexBuffer object is created.
  23789. * 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.
  23790. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23791. *
  23792. * Possible `kind` values :
  23793. * - BABYLON.VertexBuffer.PositionKind
  23794. * - BABYLON.VertexBuffer.UVKind
  23795. * - BABYLON.VertexBuffer.UV2Kind
  23796. * - BABYLON.VertexBuffer.UV3Kind
  23797. * - BABYLON.VertexBuffer.UV4Kind
  23798. * - BABYLON.VertexBuffer.UV5Kind
  23799. * - BABYLON.VertexBuffer.UV6Kind
  23800. * - BABYLON.VertexBuffer.ColorKind
  23801. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23802. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23803. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23804. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23805. *
  23806. * Returns the Mesh.
  23807. */
  23808. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23809. if (!this._geometry) {
  23810. return this;
  23811. }
  23812. if (!makeItUnique) {
  23813. this._geometry.updateVerticesData(kind, data, updateExtends);
  23814. }
  23815. else {
  23816. this.makeGeometryUnique();
  23817. this.updateVerticesData(kind, data, updateExtends, false);
  23818. }
  23819. return this;
  23820. };
  23821. /**
  23822. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23823. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23824. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23825. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23826. * Returns the Mesh.
  23827. */
  23828. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23829. if (computeNormals === void 0) { computeNormals = true; }
  23830. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23831. if (!positions) {
  23832. return this;
  23833. }
  23834. positionFunction(positions);
  23835. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23836. if (computeNormals) {
  23837. var indices = this.getIndices();
  23838. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23839. if (!normals) {
  23840. return this;
  23841. }
  23842. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23843. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23844. }
  23845. return this;
  23846. };
  23847. /**
  23848. * Creates a un-shared specific occurence of the geometry for the mesh.
  23849. * Returns the Mesh.
  23850. */
  23851. Mesh.prototype.makeGeometryUnique = function () {
  23852. if (!this._geometry) {
  23853. return this;
  23854. }
  23855. var oldGeometry = this._geometry;
  23856. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23857. oldGeometry.releaseForMesh(this, true);
  23858. geometry.applyToMesh(this);
  23859. return this;
  23860. };
  23861. /**
  23862. * Sets the mesh indices.
  23863. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23864. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23865. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23866. * This method creates a new index buffer each call.
  23867. * Returns the Mesh.
  23868. */
  23869. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23870. if (totalVertices === void 0) { totalVertices = null; }
  23871. if (updatable === void 0) { updatable = false; }
  23872. if (!this._geometry) {
  23873. var vertexData = new BABYLON.VertexData();
  23874. vertexData.indices = indices;
  23875. var scene = this.getScene();
  23876. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23877. }
  23878. else {
  23879. this._geometry.setIndices(indices, totalVertices, updatable);
  23880. }
  23881. return this;
  23882. };
  23883. /**
  23884. * Update the current index buffer
  23885. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23886. * Returns the Mesh.
  23887. */
  23888. Mesh.prototype.updateIndices = function (indices, offset) {
  23889. if (!this._geometry) {
  23890. return this;
  23891. }
  23892. this._geometry.updateIndices(indices, offset);
  23893. return this;
  23894. };
  23895. /**
  23896. * Invert the geometry to move from a right handed system to a left handed one.
  23897. * Returns the Mesh.
  23898. */
  23899. Mesh.prototype.toLeftHanded = function () {
  23900. if (!this._geometry) {
  23901. return this;
  23902. }
  23903. this._geometry.toLeftHanded();
  23904. return this;
  23905. };
  23906. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23907. if (!this._geometry) {
  23908. return this;
  23909. }
  23910. var engine = this.getScene().getEngine();
  23911. // Wireframe
  23912. var indexToBind;
  23913. if (this._unIndexed) {
  23914. indexToBind = null;
  23915. }
  23916. else {
  23917. switch (fillMode) {
  23918. case BABYLON.Material.PointFillMode:
  23919. indexToBind = null;
  23920. break;
  23921. case BABYLON.Material.WireFrameFillMode:
  23922. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23923. break;
  23924. default:
  23925. case BABYLON.Material.TriangleFillMode:
  23926. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23927. break;
  23928. }
  23929. }
  23930. // VBOs
  23931. this._geometry._bind(effect, indexToBind);
  23932. return this;
  23933. };
  23934. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23935. if (alternate === void 0) { alternate = false; }
  23936. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23937. return this;
  23938. }
  23939. this.onBeforeDrawObservable.notifyObservers(this);
  23940. var scene = this.getScene();
  23941. var engine = scene.getEngine();
  23942. // Draw order
  23943. switch (fillMode) {
  23944. case BABYLON.Material.PointFillMode:
  23945. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23946. break;
  23947. case BABYLON.Material.WireFrameFillMode:
  23948. if (this._unIndexed) {
  23949. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23950. }
  23951. else {
  23952. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23953. }
  23954. break;
  23955. default:
  23956. if (this._unIndexed) {
  23957. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23958. }
  23959. else {
  23960. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23961. }
  23962. }
  23963. if (scene._isAlternateRenderingEnabled && !alternate) {
  23964. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23965. if (!effect || !scene.activeCamera) {
  23966. return this;
  23967. }
  23968. scene._switchToAlternateCameraConfiguration(true);
  23969. this._effectiveMaterial.bindView(effect);
  23970. this._effectiveMaterial.bindViewProjection(effect);
  23971. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23972. this._draw(subMesh, fillMode, instancesCount, true);
  23973. engine.setViewport(scene.activeCamera.viewport);
  23974. scene._switchToAlternateCameraConfiguration(false);
  23975. this._effectiveMaterial.bindView(effect);
  23976. this._effectiveMaterial.bindViewProjection(effect);
  23977. }
  23978. return this;
  23979. };
  23980. /**
  23981. * Registers for this mesh a javascript function called just before the rendering process.
  23982. * This function is passed the current mesh.
  23983. * Return the Mesh.
  23984. */
  23985. Mesh.prototype.registerBeforeRender = function (func) {
  23986. this.onBeforeRenderObservable.add(func);
  23987. return this;
  23988. };
  23989. /**
  23990. * Disposes a previously registered javascript function called before the rendering.
  23991. * This function is passed the current mesh.
  23992. * Returns the Mesh.
  23993. */
  23994. Mesh.prototype.unregisterBeforeRender = function (func) {
  23995. this.onBeforeRenderObservable.removeCallback(func);
  23996. return this;
  23997. };
  23998. /**
  23999. * Registers for this mesh a javascript function called just after the rendering is complete.
  24000. * This function is passed the current mesh.
  24001. * Returns the Mesh.
  24002. */
  24003. Mesh.prototype.registerAfterRender = function (func) {
  24004. this.onAfterRenderObservable.add(func);
  24005. return this;
  24006. };
  24007. /**
  24008. * Disposes a previously registered javascript function called after the rendering.
  24009. * This function is passed the current mesh.
  24010. * Return the Mesh.
  24011. */
  24012. Mesh.prototype.unregisterAfterRender = function (func) {
  24013. this.onAfterRenderObservable.removeCallback(func);
  24014. return this;
  24015. };
  24016. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24017. var scene = this.getScene();
  24018. this._batchCache.mustReturn = false;
  24019. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24020. this._batchCache.visibleInstances[subMeshId] = null;
  24021. if (this._visibleInstances) {
  24022. var currentRenderId = scene.getRenderId();
  24023. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24024. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24025. var selfRenderId = this._renderId;
  24026. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24027. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24028. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24029. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24030. }
  24031. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24032. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24033. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24034. this._batchCache.mustReturn = true;
  24035. return this._batchCache;
  24036. }
  24037. if (currentRenderId !== selfRenderId) {
  24038. this._batchCache.renderSelf[subMeshId] = false;
  24039. }
  24040. }
  24041. this._renderIdForInstances[subMeshId] = currentRenderId;
  24042. }
  24043. return this._batchCache;
  24044. };
  24045. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24046. var visibleInstances = batch.visibleInstances[subMesh._id];
  24047. if (!visibleInstances) {
  24048. return this;
  24049. }
  24050. var matricesCount = visibleInstances.length + 1;
  24051. var bufferSize = matricesCount * 16 * 4;
  24052. var currentInstancesBufferSize = this._instancesBufferSize;
  24053. var instancesBuffer = this._instancesBuffer;
  24054. while (this._instancesBufferSize < bufferSize) {
  24055. this._instancesBufferSize *= 2;
  24056. }
  24057. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24058. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24059. }
  24060. var offset = 0;
  24061. var instancesCount = 0;
  24062. var world = this.getWorldMatrix();
  24063. if (batch.renderSelf[subMesh._id]) {
  24064. world.copyToArray(this._instancesData, offset);
  24065. offset += 16;
  24066. instancesCount++;
  24067. }
  24068. if (visibleInstances) {
  24069. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24070. var instance = visibleInstances[instanceIndex];
  24071. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24072. offset += 16;
  24073. instancesCount++;
  24074. }
  24075. }
  24076. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24077. if (instancesBuffer) {
  24078. instancesBuffer.dispose();
  24079. }
  24080. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24081. this._instancesBuffer = instancesBuffer;
  24082. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24083. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24084. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24085. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24086. }
  24087. else {
  24088. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24089. }
  24090. this._bind(subMesh, effect, fillMode);
  24091. this._draw(subMesh, fillMode, instancesCount);
  24092. engine.unbindInstanceAttributes();
  24093. return this;
  24094. };
  24095. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24096. var scene = this.getScene();
  24097. var engine = scene.getEngine();
  24098. if (hardwareInstancedRendering) {
  24099. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24100. }
  24101. else {
  24102. if (batch.renderSelf[subMesh._id]) {
  24103. // Draw
  24104. if (onBeforeDraw) {
  24105. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24106. }
  24107. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24108. }
  24109. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24110. if (visibleInstancesForSubMesh) {
  24111. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24112. var instance = visibleInstancesForSubMesh[instanceIndex];
  24113. // World
  24114. var world = instance.getWorldMatrix();
  24115. if (onBeforeDraw) {
  24116. onBeforeDraw(true, world, effectiveMaterial);
  24117. }
  24118. // Draw
  24119. this._draw(subMesh, fillMode);
  24120. }
  24121. }
  24122. }
  24123. return this;
  24124. };
  24125. /**
  24126. * Triggers the draw call for the mesh.
  24127. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24128. * Returns the Mesh.
  24129. */
  24130. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24131. this.checkOcclusionQuery();
  24132. if (this._isOccluded) {
  24133. return this;
  24134. }
  24135. var scene = this.getScene();
  24136. // Managing instances
  24137. var batch = this._getInstancesRenderList(subMesh._id);
  24138. if (batch.mustReturn) {
  24139. return this;
  24140. }
  24141. // Checking geometry state
  24142. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24143. return this;
  24144. }
  24145. this.onBeforeRenderObservable.notifyObservers(this);
  24146. var engine = scene.getEngine();
  24147. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24148. // Material
  24149. var material = subMesh.getMaterial();
  24150. if (!material) {
  24151. return this;
  24152. }
  24153. this._effectiveMaterial = material;
  24154. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24155. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24156. return this;
  24157. }
  24158. }
  24159. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24160. return this;
  24161. }
  24162. // Alpha mode
  24163. if (enableAlphaMode) {
  24164. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24165. }
  24166. // Outline - step 1
  24167. var savedDepthWrite = engine.getDepthWrite();
  24168. if (this.renderOutline) {
  24169. engine.setDepthWrite(false);
  24170. scene.getOutlineRenderer().render(subMesh, batch);
  24171. engine.setDepthWrite(savedDepthWrite);
  24172. }
  24173. var effect;
  24174. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24175. effect = subMesh.effect;
  24176. }
  24177. else {
  24178. effect = this._effectiveMaterial.getEffect();
  24179. }
  24180. if (!effect) {
  24181. return this;
  24182. }
  24183. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24184. if (this._effectiveMaterial.forceDepthWrite) {
  24185. engine.setDepthWrite(true);
  24186. }
  24187. // Bind
  24188. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24189. if (!hardwareInstancedRendering) {
  24190. this._bind(subMesh, effect, fillMode);
  24191. }
  24192. var world = this.getWorldMatrix();
  24193. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24194. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24195. }
  24196. else {
  24197. this._effectiveMaterial.bind(world, this);
  24198. }
  24199. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24200. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24201. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24202. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24203. }
  24204. // Draw
  24205. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24206. // Unbind
  24207. this._effectiveMaterial.unbind();
  24208. // Outline - step 2
  24209. if (this.renderOutline && savedDepthWrite) {
  24210. engine.setDepthWrite(true);
  24211. engine.setColorWrite(false);
  24212. scene.getOutlineRenderer().render(subMesh, batch);
  24213. engine.setColorWrite(true);
  24214. }
  24215. // Overlay
  24216. if (this.renderOverlay) {
  24217. var currentMode = engine.getAlphaMode();
  24218. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24219. scene.getOutlineRenderer().render(subMesh, batch, true);
  24220. engine.setAlphaMode(currentMode);
  24221. }
  24222. this.onAfterRenderObservable.notifyObservers(this);
  24223. return this;
  24224. };
  24225. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24226. if (isInstance && effectiveMaterial) {
  24227. effectiveMaterial.bindOnlyWorldMatrix(world);
  24228. }
  24229. };
  24230. /**
  24231. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24232. */
  24233. Mesh.prototype.getEmittedParticleSystems = function () {
  24234. var results = new Array();
  24235. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24236. var particleSystem = this.getScene().particleSystems[index];
  24237. if (particleSystem.emitter === this) {
  24238. results.push(particleSystem);
  24239. }
  24240. }
  24241. return results;
  24242. };
  24243. /**
  24244. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24245. */
  24246. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24247. var results = new Array();
  24248. var descendants = this.getDescendants();
  24249. descendants.push(this);
  24250. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24251. var particleSystem = this.getScene().particleSystems[index];
  24252. var emitter = particleSystem.emitter;
  24253. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24254. results.push(particleSystem);
  24255. }
  24256. }
  24257. return results;
  24258. };
  24259. Mesh.prototype._checkDelayState = function () {
  24260. var scene = this.getScene();
  24261. if (this._geometry) {
  24262. this._geometry.load(scene);
  24263. }
  24264. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24266. this._queueLoad(this, scene);
  24267. }
  24268. return this;
  24269. };
  24270. Mesh.prototype._queueLoad = function (mesh, scene) {
  24271. var _this = this;
  24272. scene._addPendingData(mesh);
  24273. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24274. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24275. if (data instanceof ArrayBuffer) {
  24276. _this._delayLoadingFunction(data, _this);
  24277. }
  24278. else {
  24279. _this._delayLoadingFunction(JSON.parse(data), _this);
  24280. }
  24281. _this.instances.forEach(function (instance) {
  24282. instance._syncSubMeshes();
  24283. });
  24284. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24285. scene._removePendingData(_this);
  24286. }, function () { }, scene.database, getBinaryData);
  24287. return this;
  24288. };
  24289. /**
  24290. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24291. */
  24292. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24293. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24294. return false;
  24295. }
  24296. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24297. return false;
  24298. }
  24299. this._checkDelayState();
  24300. return true;
  24301. };
  24302. /**
  24303. * Sets the mesh material by the material or multiMaterial `id` property.
  24304. * The material `id` is a string identifying the material or the multiMaterial.
  24305. * This method returns the Mesh.
  24306. */
  24307. Mesh.prototype.setMaterialByID = function (id) {
  24308. var materials = this.getScene().materials;
  24309. var index;
  24310. for (index = materials.length - 1; index > -1; index--) {
  24311. if (materials[index].id === id) {
  24312. this.material = materials[index];
  24313. return this;
  24314. }
  24315. }
  24316. // Multi
  24317. var multiMaterials = this.getScene().multiMaterials;
  24318. for (index = multiMaterials.length - 1; index > -1; index--) {
  24319. if (multiMaterials[index].id === id) {
  24320. this.material = multiMaterials[index];
  24321. return this;
  24322. }
  24323. }
  24324. return this;
  24325. };
  24326. /**
  24327. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24328. */
  24329. Mesh.prototype.getAnimatables = function () {
  24330. var results = new Array();
  24331. if (this.material) {
  24332. results.push(this.material);
  24333. }
  24334. if (this.skeleton) {
  24335. results.push(this.skeleton);
  24336. }
  24337. return results;
  24338. };
  24339. /**
  24340. * Modifies the mesh geometry according to the passed transformation matrix.
  24341. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24342. * The mesh normals are modified accordingly the same transformation.
  24343. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24344. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24345. * Returns the Mesh.
  24346. */
  24347. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24348. // Position
  24349. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24350. return this;
  24351. }
  24352. var submeshes = this.subMeshes.splice(0);
  24353. this._resetPointsArrayCache();
  24354. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24355. var temp = new Array();
  24356. var index;
  24357. for (index = 0; index < data.length; index += 3) {
  24358. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24359. }
  24360. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24361. // Normals
  24362. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24363. return this;
  24364. }
  24365. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24366. temp = [];
  24367. for (index = 0; index < data.length; index += 3) {
  24368. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24369. }
  24370. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24371. // flip faces?
  24372. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24373. this.flipFaces();
  24374. }
  24375. // Restore submeshes
  24376. this.releaseSubMeshes();
  24377. this.subMeshes = submeshes;
  24378. return this;
  24379. };
  24380. /**
  24381. * Modifies the mesh geometry according to its own current World Matrix.
  24382. * The mesh World Matrix is then reset.
  24383. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24384. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24385. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24386. * Returns the Mesh.
  24387. */
  24388. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24389. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24390. this.scaling.copyFromFloats(1, 1, 1);
  24391. this.position.copyFromFloats(0, 0, 0);
  24392. this.rotation.copyFromFloats(0, 0, 0);
  24393. //only if quaternion is already set
  24394. if (this.rotationQuaternion) {
  24395. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24396. }
  24397. this._worldMatrix = BABYLON.Matrix.Identity();
  24398. return this;
  24399. };
  24400. Object.defineProperty(Mesh.prototype, "_positions", {
  24401. // Cache
  24402. get: function () {
  24403. if (this._geometry) {
  24404. return this._geometry._positions;
  24405. }
  24406. return null;
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Mesh.prototype._resetPointsArrayCache = function () {
  24412. if (this._geometry) {
  24413. this._geometry._resetPointsArrayCache();
  24414. }
  24415. return this;
  24416. };
  24417. Mesh.prototype._generatePointsArray = function () {
  24418. if (this._geometry) {
  24419. return this._geometry._generatePointsArray();
  24420. }
  24421. return false;
  24422. };
  24423. /**
  24424. * Returns a new Mesh object generated from the current mesh properties.
  24425. * This method must not get confused with createInstance().
  24426. * The parameter `name` is a string, the name given to the new mesh.
  24427. * The optional parameter `newParent` can be any Node object (default `null`).
  24428. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24429. * 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.
  24430. */
  24431. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24432. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24433. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24434. };
  24435. /**
  24436. * Disposes the Mesh.
  24437. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24438. * Returns nothing.
  24439. */
  24440. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24441. var _this = this;
  24442. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24443. this.morphTargetManager = null;
  24444. if (this._geometry) {
  24445. this._geometry.releaseForMesh(this, true);
  24446. }
  24447. // Sources
  24448. var meshes = this.getScene().meshes;
  24449. meshes.forEach(function (abstractMesh) {
  24450. var mesh = abstractMesh;
  24451. if (mesh._source && mesh._source === _this) {
  24452. mesh._source = null;
  24453. }
  24454. });
  24455. this._source = null;
  24456. // Instances
  24457. if (this._instancesBuffer) {
  24458. this._instancesBuffer.dispose();
  24459. this._instancesBuffer = null;
  24460. }
  24461. while (this.instances.length) {
  24462. this.instances[0].dispose();
  24463. }
  24464. // Highlight layers.
  24465. var highlightLayers = this.getScene().highlightLayers;
  24466. for (var i = 0; i < highlightLayers.length; i++) {
  24467. var highlightLayer = highlightLayers[i];
  24468. if (highlightLayer) {
  24469. highlightLayer.removeMesh(this);
  24470. highlightLayer.removeExcludedMesh(this);
  24471. }
  24472. }
  24473. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24474. };
  24475. /**
  24476. * Modifies the mesh geometry according to a displacement map.
  24477. * 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.
  24478. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24479. * This method returns nothing.
  24480. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24481. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24482. * 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.
  24483. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24484. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24485. *
  24486. * Returns the Mesh.
  24487. */
  24488. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24489. var _this = this;
  24490. var scene = this.getScene();
  24491. var onload = function (img) {
  24492. // Getting height map data
  24493. var canvas = document.createElement("canvas");
  24494. var context = canvas.getContext("2d");
  24495. var heightMapWidth = img.width;
  24496. var heightMapHeight = img.height;
  24497. canvas.width = heightMapWidth;
  24498. canvas.height = heightMapHeight;
  24499. context.drawImage(img, 0, 0);
  24500. // Create VertexData from map data
  24501. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24502. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24503. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24504. //execute success callback, if set
  24505. if (onSuccess) {
  24506. onSuccess(_this);
  24507. }
  24508. };
  24509. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24510. return this;
  24511. };
  24512. /**
  24513. * Modifies the mesh geometry according to a displacementMap buffer.
  24514. * 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.
  24515. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24516. * This method returns nothing.
  24517. * 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.
  24518. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24519. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24520. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24521. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24522. *
  24523. * Returns the Mesh.
  24524. */
  24525. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24526. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24527. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24528. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24529. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24530. return this;
  24531. }
  24532. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24533. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24534. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24535. var position = BABYLON.Vector3.Zero();
  24536. var normal = BABYLON.Vector3.Zero();
  24537. var uv = BABYLON.Vector2.Zero();
  24538. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24539. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24540. for (var index = 0; index < positions.length; index += 3) {
  24541. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24542. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24543. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24544. // Compute height
  24545. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24546. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24547. var pos = (u + v * heightMapWidth) * 4;
  24548. var r = buffer[pos] / 255.0;
  24549. var g = buffer[pos + 1] / 255.0;
  24550. var b = buffer[pos + 2] / 255.0;
  24551. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24552. normal.normalize();
  24553. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24554. position = position.add(normal);
  24555. position.toArray(positions, index);
  24556. }
  24557. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24558. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24559. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24560. return this;
  24561. };
  24562. /**
  24563. * Modify the mesh to get a flat shading rendering.
  24564. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24565. * This method returns the Mesh.
  24566. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24567. */
  24568. Mesh.prototype.convertToFlatShadedMesh = function () {
  24569. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24570. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24571. var kinds = this.getVerticesDataKinds();
  24572. var vbs = {};
  24573. var data = {};
  24574. var newdata = {};
  24575. var updatableNormals = false;
  24576. var kindIndex;
  24577. var kind;
  24578. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24579. kind = kinds[kindIndex];
  24580. var vertexBuffer = this.getVertexBuffer(kind);
  24581. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24582. updatableNormals = vertexBuffer.isUpdatable();
  24583. kinds.splice(kindIndex, 1);
  24584. kindIndex--;
  24585. continue;
  24586. }
  24587. vbs[kind] = vertexBuffer;
  24588. data[kind] = vbs[kind].getData();
  24589. newdata[kind] = [];
  24590. }
  24591. // Save previous submeshes
  24592. var previousSubmeshes = this.subMeshes.slice(0);
  24593. var indices = this.getIndices();
  24594. var totalIndices = this.getTotalIndices();
  24595. // Generating unique vertices per face
  24596. var index;
  24597. for (index = 0; index < totalIndices; index++) {
  24598. var vertexIndex = indices[index];
  24599. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24600. kind = kinds[kindIndex];
  24601. var stride = vbs[kind].getStrideSize();
  24602. for (var offset = 0; offset < stride; offset++) {
  24603. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24604. }
  24605. }
  24606. }
  24607. // Updating faces & normal
  24608. var normals = [];
  24609. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24610. for (index = 0; index < totalIndices; index += 3) {
  24611. indices[index] = index;
  24612. indices[index + 1] = index + 1;
  24613. indices[index + 2] = index + 2;
  24614. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24615. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24616. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24617. var p1p2 = p1.subtract(p2);
  24618. var p3p2 = p3.subtract(p2);
  24619. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24620. // Store same normals for every vertex
  24621. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24622. normals.push(normal.x);
  24623. normals.push(normal.y);
  24624. normals.push(normal.z);
  24625. }
  24626. }
  24627. this.setIndices(indices);
  24628. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24629. // Updating vertex buffers
  24630. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24631. kind = kinds[kindIndex];
  24632. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24633. }
  24634. // Updating submeshes
  24635. this.releaseSubMeshes();
  24636. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24637. var previousOne = previousSubmeshes[submeshIndex];
  24638. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24639. }
  24640. this.synchronizeInstances();
  24641. return this;
  24642. };
  24643. /**
  24644. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24645. * In other words, more vertices, no more indices and a single bigger VBO.
  24646. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24647. * Returns the Mesh.
  24648. */
  24649. Mesh.prototype.convertToUnIndexedMesh = function () {
  24650. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24651. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24652. var kinds = this.getVerticesDataKinds();
  24653. var vbs = {};
  24654. var data = {};
  24655. var newdata = {};
  24656. var kindIndex;
  24657. var kind;
  24658. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24659. kind = kinds[kindIndex];
  24660. var vertexBuffer = this.getVertexBuffer(kind);
  24661. vbs[kind] = vertexBuffer;
  24662. data[kind] = vbs[kind].getData();
  24663. newdata[kind] = [];
  24664. }
  24665. // Save previous submeshes
  24666. var previousSubmeshes = this.subMeshes.slice(0);
  24667. var indices = this.getIndices();
  24668. var totalIndices = this.getTotalIndices();
  24669. // Generating unique vertices per face
  24670. var index;
  24671. for (index = 0; index < totalIndices; index++) {
  24672. var vertexIndex = indices[index];
  24673. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24674. kind = kinds[kindIndex];
  24675. var stride = vbs[kind].getStrideSize();
  24676. for (var offset = 0; offset < stride; offset++) {
  24677. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24678. }
  24679. }
  24680. }
  24681. // Updating indices
  24682. for (index = 0; index < totalIndices; index += 3) {
  24683. indices[index] = index;
  24684. indices[index + 1] = index + 1;
  24685. indices[index + 2] = index + 2;
  24686. }
  24687. this.setIndices(indices);
  24688. // Updating vertex buffers
  24689. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24690. kind = kinds[kindIndex];
  24691. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24692. }
  24693. // Updating submeshes
  24694. this.releaseSubMeshes();
  24695. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24696. var previousOne = previousSubmeshes[submeshIndex];
  24697. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24698. }
  24699. this._unIndexed = true;
  24700. this.synchronizeInstances();
  24701. return this;
  24702. };
  24703. /**
  24704. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24705. * This method returns the Mesh.
  24706. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24707. */
  24708. Mesh.prototype.flipFaces = function (flipNormals) {
  24709. if (flipNormals === void 0) { flipNormals = false; }
  24710. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24711. var i;
  24712. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24713. for (i = 0; i < vertex_data.normals.length; i++) {
  24714. vertex_data.normals[i] *= -1;
  24715. }
  24716. }
  24717. if (vertex_data.indices) {
  24718. var temp;
  24719. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24720. // reassign indices
  24721. temp = vertex_data.indices[i + 1];
  24722. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24723. vertex_data.indices[i + 2] = temp;
  24724. }
  24725. }
  24726. vertex_data.applyToMesh(this);
  24727. return this;
  24728. };
  24729. // Instances
  24730. /**
  24731. * Creates a new InstancedMesh object from the mesh model.
  24732. * An instance shares the same properties and the same material than its model.
  24733. * Only these properties of each instance can then be set individually :
  24734. * - position
  24735. * - rotation
  24736. * - rotationQuaternion
  24737. * - setPivotMatrix
  24738. * - scaling
  24739. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24740. * Warning : this method is not supported for Line mesh and LineSystem
  24741. */
  24742. Mesh.prototype.createInstance = function (name) {
  24743. return new BABYLON.InstancedMesh(name, this);
  24744. };
  24745. /**
  24746. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24747. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24748. * This method returns the Mesh.
  24749. */
  24750. Mesh.prototype.synchronizeInstances = function () {
  24751. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24752. var instance = this.instances[instanceIndex];
  24753. instance._syncSubMeshes();
  24754. }
  24755. return this;
  24756. };
  24757. /**
  24758. * Simplify the mesh according to the given array of settings.
  24759. * Function will return immediately and will simplify async. It returns the Mesh.
  24760. * @param settings a collection of simplification settings.
  24761. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24762. * @param type the type of simplification to run.
  24763. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24764. */
  24765. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24766. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24767. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24768. this.getScene().simplificationQueue.addTask({
  24769. settings: settings,
  24770. parallelProcessing: parallelProcessing,
  24771. mesh: this,
  24772. simplificationType: simplificationType,
  24773. successCallback: successCallback
  24774. });
  24775. return this;
  24776. };
  24777. /**
  24778. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24779. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24780. * This should be used together with the simplification to avoid disappearing triangles.
  24781. * Returns the Mesh.
  24782. * @param successCallback an optional success callback to be called after the optimization finished.
  24783. */
  24784. Mesh.prototype.optimizeIndices = function (successCallback) {
  24785. var _this = this;
  24786. var indices = this.getIndices();
  24787. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24788. if (!positions || !indices) {
  24789. return this;
  24790. }
  24791. var vectorPositions = new Array();
  24792. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24793. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24794. }
  24795. var dupes = new Array();
  24796. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24797. var realPos = vectorPositions.length - 1 - iteration;
  24798. var testedPosition = vectorPositions[realPos];
  24799. for (var j = 0; j < realPos; ++j) {
  24800. var againstPosition = vectorPositions[j];
  24801. if (testedPosition.equals(againstPosition)) {
  24802. dupes[realPos] = j;
  24803. break;
  24804. }
  24805. }
  24806. }, function () {
  24807. for (var i = 0; i < indices.length; ++i) {
  24808. indices[i] = dupes[indices[i]] || indices[i];
  24809. }
  24810. //indices are now reordered
  24811. var originalSubMeshes = _this.subMeshes.slice(0);
  24812. _this.setIndices(indices);
  24813. _this.subMeshes = originalSubMeshes;
  24814. if (successCallback) {
  24815. successCallback(_this);
  24816. }
  24817. });
  24818. return this;
  24819. };
  24820. Mesh.prototype.serialize = function (serializationObject) {
  24821. serializationObject.name = this.name;
  24822. serializationObject.id = this.id;
  24823. serializationObject.type = this.getClassName();
  24824. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24825. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24826. }
  24827. serializationObject.position = this.position.asArray();
  24828. if (this.rotationQuaternion) {
  24829. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24830. }
  24831. else if (this.rotation) {
  24832. serializationObject.rotation = this.rotation.asArray();
  24833. }
  24834. serializationObject.scaling = this.scaling.asArray();
  24835. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24836. serializationObject.isEnabled = this.isEnabled();
  24837. serializationObject.isVisible = this.isVisible;
  24838. serializationObject.infiniteDistance = this.infiniteDistance;
  24839. serializationObject.pickable = this.isPickable;
  24840. serializationObject.receiveShadows = this.receiveShadows;
  24841. serializationObject.billboardMode = this.billboardMode;
  24842. serializationObject.visibility = this.visibility;
  24843. serializationObject.checkCollisions = this.checkCollisions;
  24844. serializationObject.isBlocker = this.isBlocker;
  24845. // Parent
  24846. if (this.parent) {
  24847. serializationObject.parentId = this.parent.id;
  24848. }
  24849. // Geometry
  24850. var geometry = this._geometry;
  24851. if (geometry) {
  24852. var geometryId = geometry.id;
  24853. serializationObject.geometryId = geometryId;
  24854. // SubMeshes
  24855. serializationObject.subMeshes = [];
  24856. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24857. var subMesh = this.subMeshes[subIndex];
  24858. serializationObject.subMeshes.push({
  24859. materialIndex: subMesh.materialIndex,
  24860. verticesStart: subMesh.verticesStart,
  24861. verticesCount: subMesh.verticesCount,
  24862. indexStart: subMesh.indexStart,
  24863. indexCount: subMesh.indexCount
  24864. });
  24865. }
  24866. }
  24867. // Material
  24868. if (this.material) {
  24869. serializationObject.materialId = this.material.id;
  24870. }
  24871. else {
  24872. this.material = null;
  24873. }
  24874. // Morph targets
  24875. if (this.morphTargetManager) {
  24876. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24877. }
  24878. // Skeleton
  24879. if (this.skeleton) {
  24880. serializationObject.skeletonId = this.skeleton.id;
  24881. }
  24882. // Physics
  24883. //TODO implement correct serialization for physics impostors.
  24884. var impostor = this.getPhysicsImpostor();
  24885. if (impostor) {
  24886. serializationObject.physicsMass = impostor.getParam("mass");
  24887. serializationObject.physicsFriction = impostor.getParam("friction");
  24888. serializationObject.physicsRestitution = impostor.getParam("mass");
  24889. serializationObject.physicsImpostor = impostor.type;
  24890. }
  24891. // Metadata
  24892. if (this.metadata) {
  24893. serializationObject.metadata = this.metadata;
  24894. }
  24895. // Instances
  24896. serializationObject.instances = [];
  24897. for (var index = 0; index < this.instances.length; index++) {
  24898. var instance = this.instances[index];
  24899. var serializationInstance = {
  24900. name: instance.name,
  24901. position: instance.position.asArray(),
  24902. scaling: instance.scaling.asArray()
  24903. };
  24904. if (instance.rotationQuaternion) {
  24905. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24906. }
  24907. else if (instance.rotation) {
  24908. serializationInstance.rotation = instance.rotation.asArray();
  24909. }
  24910. serializationObject.instances.push(serializationInstance);
  24911. // Animations
  24912. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24913. serializationInstance.ranges = instance.serializeAnimationRanges();
  24914. }
  24915. //
  24916. // Animations
  24917. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24918. serializationObject.ranges = this.serializeAnimationRanges();
  24919. // Layer mask
  24920. serializationObject.layerMask = this.layerMask;
  24921. // Alpha
  24922. serializationObject.alphaIndex = this.alphaIndex;
  24923. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24924. // Overlay
  24925. serializationObject.overlayAlpha = this.overlayAlpha;
  24926. serializationObject.overlayColor = this.overlayColor.asArray();
  24927. serializationObject.renderOverlay = this.renderOverlay;
  24928. // Fog
  24929. serializationObject.applyFog = this.applyFog;
  24930. // Action Manager
  24931. if (this.actionManager) {
  24932. serializationObject.actions = this.actionManager.serialize(this.name);
  24933. }
  24934. };
  24935. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24936. if (!this.geometry) {
  24937. return;
  24938. }
  24939. this._markSubMeshesAsAttributesDirty();
  24940. var morphTargetManager = this._morphTargetManager;
  24941. if (morphTargetManager && morphTargetManager.vertexCount) {
  24942. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24943. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24944. this.morphTargetManager = null;
  24945. return;
  24946. }
  24947. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24948. var morphTarget = morphTargetManager.getActiveTarget(index);
  24949. var positions = morphTarget.getPositions();
  24950. if (!positions) {
  24951. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24952. return;
  24953. }
  24954. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24955. var normals = morphTarget.getNormals();
  24956. if (normals) {
  24957. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24958. }
  24959. var tangents = morphTarget.getTangents();
  24960. if (tangents) {
  24961. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24962. }
  24963. }
  24964. }
  24965. else {
  24966. var index = 0;
  24967. // Positions
  24968. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24969. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24970. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24971. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24972. }
  24973. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24974. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24975. }
  24976. index++;
  24977. }
  24978. }
  24979. };
  24980. // Statics
  24981. /**
  24982. * Returns a new Mesh object parsed from the source provided.
  24983. * The parameter `parsedMesh` is the source.
  24984. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24985. */
  24986. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24987. var mesh;
  24988. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24989. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24990. }
  24991. else {
  24992. mesh = new Mesh(parsedMesh.name, scene);
  24993. }
  24994. mesh.id = parsedMesh.id;
  24995. if (BABYLON.Tags) {
  24996. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24997. }
  24998. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24999. if (parsedMesh.metadata !== undefined) {
  25000. mesh.metadata = parsedMesh.metadata;
  25001. }
  25002. if (parsedMesh.rotationQuaternion) {
  25003. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25004. }
  25005. else if (parsedMesh.rotation) {
  25006. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25007. }
  25008. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25009. if (parsedMesh.localMatrix) {
  25010. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25011. }
  25012. else if (parsedMesh.pivotMatrix) {
  25013. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25014. }
  25015. mesh.setEnabled(parsedMesh.isEnabled);
  25016. mesh.isVisible = parsedMesh.isVisible;
  25017. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25018. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25019. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25020. if (parsedMesh.applyFog !== undefined) {
  25021. mesh.applyFog = parsedMesh.applyFog;
  25022. }
  25023. if (parsedMesh.pickable !== undefined) {
  25024. mesh.isPickable = parsedMesh.pickable;
  25025. }
  25026. if (parsedMesh.alphaIndex !== undefined) {
  25027. mesh.alphaIndex = parsedMesh.alphaIndex;
  25028. }
  25029. mesh.receiveShadows = parsedMesh.receiveShadows;
  25030. mesh.billboardMode = parsedMesh.billboardMode;
  25031. if (parsedMesh.visibility !== undefined) {
  25032. mesh.visibility = parsedMesh.visibility;
  25033. }
  25034. mesh.checkCollisions = parsedMesh.checkCollisions;
  25035. if (parsedMesh.isBlocker !== undefined) {
  25036. mesh.isBlocker = parsedMesh.isBlocker;
  25037. }
  25038. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25039. // freezeWorldMatrix
  25040. if (parsedMesh.freezeWorldMatrix) {
  25041. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25042. }
  25043. // Parent
  25044. if (parsedMesh.parentId) {
  25045. mesh._waitingParentId = parsedMesh.parentId;
  25046. }
  25047. // Actions
  25048. if (parsedMesh.actions !== undefined) {
  25049. mesh._waitingActions = parsedMesh.actions;
  25050. }
  25051. // Overlay
  25052. if (parsedMesh.overlayAlpha !== undefined) {
  25053. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25054. }
  25055. if (parsedMesh.overlayColor !== undefined) {
  25056. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25057. }
  25058. if (parsedMesh.renderOverlay !== undefined) {
  25059. mesh.renderOverlay = parsedMesh.renderOverlay;
  25060. }
  25061. // Geometry
  25062. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25063. if (parsedMesh.delayLoadingFile) {
  25064. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25065. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25066. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25067. if (parsedMesh._binaryInfo) {
  25068. mesh._binaryInfo = parsedMesh._binaryInfo;
  25069. }
  25070. mesh._delayInfo = [];
  25071. if (parsedMesh.hasUVs) {
  25072. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25073. }
  25074. if (parsedMesh.hasUVs2) {
  25075. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25076. }
  25077. if (parsedMesh.hasUVs3) {
  25078. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25079. }
  25080. if (parsedMesh.hasUVs4) {
  25081. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25082. }
  25083. if (parsedMesh.hasUVs5) {
  25084. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25085. }
  25086. if (parsedMesh.hasUVs6) {
  25087. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25088. }
  25089. if (parsedMesh.hasColors) {
  25090. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25091. }
  25092. if (parsedMesh.hasMatricesIndices) {
  25093. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25094. }
  25095. if (parsedMesh.hasMatricesWeights) {
  25096. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25097. }
  25098. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25099. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25100. mesh._checkDelayState();
  25101. }
  25102. }
  25103. else {
  25104. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25105. }
  25106. // Material
  25107. if (parsedMesh.materialId) {
  25108. mesh.setMaterialByID(parsedMesh.materialId);
  25109. }
  25110. else {
  25111. mesh.material = null;
  25112. }
  25113. // Morph targets
  25114. if (parsedMesh.morphTargetManagerId > -1) {
  25115. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25116. }
  25117. // Skeleton
  25118. if (parsedMesh.skeletonId > -1) {
  25119. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25120. if (parsedMesh.numBoneInfluencers) {
  25121. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25122. }
  25123. }
  25124. // Animations
  25125. if (parsedMesh.animations) {
  25126. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25127. var parsedAnimation = parsedMesh.animations[animationIndex];
  25128. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25129. }
  25130. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25131. }
  25132. if (parsedMesh.autoAnimate) {
  25133. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25134. }
  25135. // Layer Mask
  25136. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25137. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25138. }
  25139. else {
  25140. mesh.layerMask = 0x0FFFFFFF;
  25141. }
  25142. // Physics
  25143. if (parsedMesh.physicsImpostor) {
  25144. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25145. mass: parsedMesh.physicsMass,
  25146. friction: parsedMesh.physicsFriction,
  25147. restitution: parsedMesh.physicsRestitution
  25148. }, scene);
  25149. }
  25150. // Instances
  25151. if (parsedMesh.instances) {
  25152. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25153. var parsedInstance = parsedMesh.instances[index];
  25154. var instance = mesh.createInstance(parsedInstance.name);
  25155. if (BABYLON.Tags) {
  25156. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25157. }
  25158. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25159. if (parsedInstance.parentId) {
  25160. instance._waitingParentId = parsedInstance.parentId;
  25161. }
  25162. if (parsedInstance.rotationQuaternion) {
  25163. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25164. }
  25165. else if (parsedInstance.rotation) {
  25166. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25167. }
  25168. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25169. instance.checkCollisions = mesh.checkCollisions;
  25170. if (parsedMesh.animations) {
  25171. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25172. parsedAnimation = parsedMesh.animations[animationIndex];
  25173. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25174. }
  25175. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25176. }
  25177. }
  25178. }
  25179. return mesh;
  25180. };
  25181. /**
  25182. * Creates a ribbon mesh.
  25183. * Please consider using the same method from the MeshBuilder class instead.
  25184. * 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.
  25185. *
  25186. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25187. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25188. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25189. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25190. * 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.
  25191. * 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.
  25192. * 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
  25193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25196. */
  25197. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25198. if (closeArray === void 0) { closeArray = false; }
  25199. if (updatable === void 0) { updatable = false; }
  25200. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25201. pathArray: pathArray,
  25202. closeArray: closeArray,
  25203. closePath: closePath,
  25204. offset: offset,
  25205. updatable: updatable,
  25206. sideOrientation: sideOrientation,
  25207. instance: instance
  25208. }, scene);
  25209. };
  25210. /**
  25211. * Creates a plane polygonal mesh. By default, this is a disc.
  25212. * Please consider using the same method from the MeshBuilder class instead.
  25213. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25214. * 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.
  25215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25218. */
  25219. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25220. if (scene === void 0) { scene = null; }
  25221. var options = {
  25222. radius: radius,
  25223. tessellation: tessellation,
  25224. sideOrientation: sideOrientation,
  25225. updatable: updatable
  25226. };
  25227. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25228. };
  25229. /**
  25230. * Creates a box mesh.
  25231. * Please consider using the same method from the MeshBuilder class instead.
  25232. * The parameter `size` sets the size (float) of each box side (default 1).
  25233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25236. */
  25237. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25238. if (scene === void 0) { scene = null; }
  25239. var options = {
  25240. size: size,
  25241. sideOrientation: sideOrientation,
  25242. updatable: updatable
  25243. };
  25244. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25245. };
  25246. /**
  25247. * Creates a sphere mesh.
  25248. * Please consider using the same method from the MeshBuilder class instead.
  25249. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25250. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25254. */
  25255. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25256. var options = {
  25257. segments: segments,
  25258. diameterX: diameter,
  25259. diameterY: diameter,
  25260. diameterZ: diameter,
  25261. sideOrientation: sideOrientation,
  25262. updatable: updatable
  25263. };
  25264. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25265. };
  25266. /**
  25267. * Creates a cylinder or a cone mesh.
  25268. * Please consider using the same method from the MeshBuilder class instead.
  25269. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25270. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25271. * 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.
  25272. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25273. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25274. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25275. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25277. */
  25278. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25279. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25280. if (scene !== undefined) {
  25281. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25282. updatable = scene;
  25283. }
  25284. scene = subdivisions;
  25285. subdivisions = 1;
  25286. }
  25287. var options = {
  25288. height: height,
  25289. diameterTop: diameterTop,
  25290. diameterBottom: diameterBottom,
  25291. tessellation: tessellation,
  25292. subdivisions: subdivisions,
  25293. sideOrientation: sideOrientation,
  25294. updatable: updatable
  25295. };
  25296. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25297. };
  25298. // Torus (Code from SharpDX.org)
  25299. /**
  25300. * Creates a torus mesh.
  25301. * Please consider using the same method from the MeshBuilder class instead.
  25302. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25303. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25304. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25308. */
  25309. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25310. var options = {
  25311. diameter: diameter,
  25312. thickness: thickness,
  25313. tessellation: tessellation,
  25314. sideOrientation: sideOrientation,
  25315. updatable: updatable
  25316. };
  25317. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25318. };
  25319. /**
  25320. * Creates a torus knot mesh.
  25321. * Please consider using the same method from the MeshBuilder class instead.
  25322. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25323. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25324. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25325. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25326. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25327. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25329. */
  25330. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25331. var options = {
  25332. radius: radius,
  25333. tube: tube,
  25334. radialSegments: radialSegments,
  25335. tubularSegments: tubularSegments,
  25336. p: p,
  25337. q: q,
  25338. sideOrientation: sideOrientation,
  25339. updatable: updatable
  25340. };
  25341. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25342. };
  25343. /**
  25344. * Creates a line mesh.
  25345. * Please consider using the same method from the MeshBuilder class instead.
  25346. * 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.
  25347. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25348. * The parameter `points` is an array successive Vector3.
  25349. * 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
  25350. * When updating an instance, remember that only point positions can change, not the number of points.
  25351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25352. */
  25353. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25354. if (scene === void 0) { scene = null; }
  25355. if (updatable === void 0) { updatable = false; }
  25356. if (instance === void 0) { instance = null; }
  25357. var options = {
  25358. points: points,
  25359. updatable: updatable,
  25360. instance: instance
  25361. };
  25362. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25363. };
  25364. /**
  25365. * Creates a dashed line mesh.
  25366. * Please consider using the same method from the MeshBuilder class instead.
  25367. * 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.
  25368. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25369. * The parameter `points` is an array successive Vector3.
  25370. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25371. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25372. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25373. * 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
  25374. * When updating an instance, remember that only point positions can change, not the number of points.
  25375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25376. */
  25377. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25378. if (scene === void 0) { scene = null; }
  25379. var options = {
  25380. points: points,
  25381. dashSize: dashSize,
  25382. gapSize: gapSize,
  25383. dashNb: dashNb,
  25384. updatable: updatable,
  25385. instance: instance
  25386. };
  25387. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25388. };
  25389. /**
  25390. * Creates a polygon mesh.
  25391. * Please consider using the same method from the MeshBuilder class instead.
  25392. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25393. * 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.
  25394. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25396. * Remember you can only change the shape positions, not their number when updating a polygon.
  25397. */
  25398. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25399. var options = {
  25400. shape: shape,
  25401. holes: holes,
  25402. updatable: updatable,
  25403. sideOrientation: sideOrientation
  25404. };
  25405. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25406. };
  25407. /**
  25408. * Creates an extruded polygon mesh, with depth in the Y direction.
  25409. * Please consider using the same method from the MeshBuilder class instead.
  25410. */
  25411. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25412. var options = {
  25413. shape: shape,
  25414. holes: holes,
  25415. depth: depth,
  25416. updatable: updatable,
  25417. sideOrientation: sideOrientation
  25418. };
  25419. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25420. };
  25421. /**
  25422. * Creates an extruded shape mesh.
  25423. * 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.
  25424. * Please consider using the same method from the MeshBuilder class instead.
  25425. *
  25426. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25427. * 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
  25428. * extruded along the Z axis.
  25429. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25430. * 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.
  25431. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25432. * 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
  25433. * 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
  25434. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25438. */
  25439. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25440. if (scene === void 0) { scene = null; }
  25441. var options = {
  25442. shape: shape,
  25443. path: path,
  25444. scale: scale,
  25445. rotation: rotation,
  25446. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25447. sideOrientation: sideOrientation,
  25448. instance: instance,
  25449. updatable: updatable
  25450. };
  25451. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25452. };
  25453. /**
  25454. * Creates an custom extruded shape mesh.
  25455. * 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.
  25456. * Please consider using the same method from the MeshBuilder class instead.
  25457. *
  25458. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25459. * 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
  25460. * extruded along the Z axis.
  25461. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25462. * 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
  25463. * and the distance of this point from the begining of the path :
  25464. * ```javascript
  25465. * var rotationFunction = function(i, distance) {
  25466. * // do things
  25467. * return rotationValue; }
  25468. * ```
  25469. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25470. * 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
  25471. * and the distance of this point from the begining of the path :
  25472. * ```javascript
  25473. * var scaleFunction = function(i, distance) {
  25474. * // do things
  25475. * return scaleValue;}
  25476. * ```
  25477. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25478. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25479. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25480. * 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
  25481. * 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
  25482. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25486. */
  25487. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25488. var options = {
  25489. shape: shape,
  25490. path: path,
  25491. scaleFunction: scaleFunction,
  25492. rotationFunction: rotationFunction,
  25493. ribbonCloseArray: ribbonCloseArray,
  25494. ribbonClosePath: ribbonClosePath,
  25495. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25496. sideOrientation: sideOrientation,
  25497. instance: instance,
  25498. updatable: updatable
  25499. };
  25500. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25501. };
  25502. /**
  25503. * Creates lathe mesh.
  25504. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25505. * Please consider using the same method from the MeshBuilder class instead.
  25506. * 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
  25507. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25508. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25509. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25513. */
  25514. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25515. var options = {
  25516. shape: shape,
  25517. radius: radius,
  25518. tessellation: tessellation,
  25519. sideOrientation: sideOrientation,
  25520. updatable: updatable
  25521. };
  25522. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25523. };
  25524. /**
  25525. * Creates a plane mesh.
  25526. * Please consider using the same method from the MeshBuilder class instead.
  25527. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25528. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25529. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25531. */
  25532. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25533. var options = {
  25534. size: size,
  25535. width: size,
  25536. height: size,
  25537. sideOrientation: sideOrientation,
  25538. updatable: updatable
  25539. };
  25540. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25541. };
  25542. /**
  25543. * Creates a ground mesh.
  25544. * Please consider using the same method from the MeshBuilder class instead.
  25545. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25546. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25548. */
  25549. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25550. var options = {
  25551. width: width,
  25552. height: height,
  25553. subdivisions: subdivisions,
  25554. updatable: updatable
  25555. };
  25556. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25557. };
  25558. /**
  25559. * Creates a tiled ground mesh.
  25560. * Please consider using the same method from the MeshBuilder class instead.
  25561. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25562. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25563. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25564. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25565. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25566. * numbers of subdivisions on the ground width and height of each tile.
  25567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25568. */
  25569. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25570. var options = {
  25571. xmin: xmin,
  25572. zmin: zmin,
  25573. xmax: xmax,
  25574. zmax: zmax,
  25575. subdivisions: subdivisions,
  25576. precision: precision,
  25577. updatable: updatable
  25578. };
  25579. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25580. };
  25581. /**
  25582. * Creates a ground mesh from a height map.
  25583. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25584. * Please consider using the same method from the MeshBuilder class instead.
  25585. * The parameter `url` sets the URL of the height map image resource.
  25586. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25587. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25588. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25589. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25590. * 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).
  25591. * This function is passed the newly built mesh :
  25592. * ```javascript
  25593. * function(mesh) { // do things
  25594. * return; }
  25595. * ```
  25596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25597. */
  25598. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25599. var options = {
  25600. width: width,
  25601. height: height,
  25602. subdivisions: subdivisions,
  25603. minHeight: minHeight,
  25604. maxHeight: maxHeight,
  25605. updatable: updatable,
  25606. onReady: onReady
  25607. };
  25608. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25609. };
  25610. /**
  25611. * Creates a tube mesh.
  25612. * 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.
  25613. * Please consider using the same method from the MeshBuilder class instead.
  25614. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25615. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25616. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25617. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25618. * 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.
  25619. * It must return a radius value (positive float) :
  25620. * ```javascript
  25621. * var radiusFunction = function(i, distance) {
  25622. * // do things
  25623. * return radius; }
  25624. * ```
  25625. * 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
  25626. * 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
  25627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25630. */
  25631. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25632. var options = {
  25633. path: path,
  25634. radius: radius,
  25635. tessellation: tessellation,
  25636. radiusFunction: radiusFunction,
  25637. arc: 1,
  25638. cap: cap,
  25639. updatable: updatable,
  25640. sideOrientation: sideOrientation,
  25641. instance: instance
  25642. };
  25643. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25644. };
  25645. /**
  25646. * Creates a polyhedron mesh.
  25647. * Please consider using the same method from the MeshBuilder class instead.
  25648. * 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
  25649. * to choose the wanted type.
  25650. * The parameter `size` (positive float, default 1) sets the polygon size.
  25651. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25652. * 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`.
  25653. * 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
  25654. * 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)`).
  25655. * 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
  25656. * 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.
  25657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25660. */
  25661. Mesh.CreatePolyhedron = function (name, options, scene) {
  25662. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25663. };
  25664. /**
  25665. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25666. * Please consider using the same method from the MeshBuilder class instead.
  25667. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25668. * 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`).
  25669. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25670. * 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.
  25671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25674. */
  25675. Mesh.CreateIcoSphere = function (name, options, scene) {
  25676. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25677. };
  25678. /**
  25679. * Creates a decal mesh.
  25680. * Please consider using the same method from the MeshBuilder class instead.
  25681. * 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.
  25682. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25683. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25684. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25685. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25686. */
  25687. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25688. var options = {
  25689. position: position,
  25690. normal: normal,
  25691. size: size,
  25692. angle: angle
  25693. };
  25694. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25695. };
  25696. // Skeletons
  25697. /**
  25698. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25699. */
  25700. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25701. if (!this._sourcePositions) {
  25702. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25703. if (!source) {
  25704. return this._sourcePositions;
  25705. }
  25706. this._sourcePositions = new Float32Array(source);
  25707. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25708. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25709. }
  25710. }
  25711. return this._sourcePositions;
  25712. };
  25713. /**
  25714. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25715. */
  25716. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25717. if (!this._sourceNormals) {
  25718. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25719. if (!source) {
  25720. return this._sourceNormals;
  25721. }
  25722. this._sourceNormals = new Float32Array(source);
  25723. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25724. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25725. }
  25726. }
  25727. return this._sourceNormals;
  25728. };
  25729. /**
  25730. * Updates the vertex buffer by applying transformation from the bones.
  25731. * Returns the Mesh.
  25732. *
  25733. * @param {skeleton} skeleton to apply
  25734. */
  25735. Mesh.prototype.applySkeleton = function (skeleton) {
  25736. if (!this.geometry) {
  25737. return this;
  25738. }
  25739. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25740. return this;
  25741. }
  25742. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25743. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25744. return this;
  25745. }
  25746. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25747. return this;
  25748. }
  25749. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25750. return this;
  25751. }
  25752. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25753. return this;
  25754. }
  25755. if (!this._sourcePositions) {
  25756. var submeshes = this.subMeshes.slice();
  25757. this.setPositionsForCPUSkinning();
  25758. this.subMeshes = submeshes;
  25759. }
  25760. if (!this._sourceNormals) {
  25761. this.setNormalsForCPUSkinning();
  25762. }
  25763. // positionsData checks for not being Float32Array will only pass at most once
  25764. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25765. if (!positionsData) {
  25766. return this;
  25767. }
  25768. if (!(positionsData instanceof Float32Array)) {
  25769. positionsData = new Float32Array(positionsData);
  25770. }
  25771. // normalsData checks for not being Float32Array will only pass at most once
  25772. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25773. if (!normalsData) {
  25774. return this;
  25775. }
  25776. if (!(normalsData instanceof Float32Array)) {
  25777. normalsData = new Float32Array(normalsData);
  25778. }
  25779. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25780. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25781. if (!matricesWeightsData || !matricesIndicesData) {
  25782. return this;
  25783. }
  25784. var needExtras = this.numBoneInfluencers > 4;
  25785. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25786. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25787. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25788. var tempVector3 = BABYLON.Vector3.Zero();
  25789. var finalMatrix = new BABYLON.Matrix();
  25790. var tempMatrix = new BABYLON.Matrix();
  25791. var matWeightIdx = 0;
  25792. var inf;
  25793. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25794. var weight;
  25795. for (inf = 0; inf < 4; inf++) {
  25796. weight = matricesWeightsData[matWeightIdx + inf];
  25797. if (weight > 0) {
  25798. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25799. finalMatrix.addToSelf(tempMatrix);
  25800. }
  25801. else
  25802. break;
  25803. }
  25804. if (needExtras) {
  25805. for (inf = 0; inf < 4; inf++) {
  25806. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25807. if (weight > 0) {
  25808. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25809. finalMatrix.addToSelf(tempMatrix);
  25810. }
  25811. else
  25812. break;
  25813. }
  25814. }
  25815. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25816. tempVector3.toArray(positionsData, index);
  25817. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25818. tempVector3.toArray(normalsData, index);
  25819. finalMatrix.reset();
  25820. }
  25821. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25822. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25823. return this;
  25824. };
  25825. // Tools
  25826. /**
  25827. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25828. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25829. */
  25830. Mesh.MinMax = function (meshes) {
  25831. var minVector = null;
  25832. var maxVector = null;
  25833. meshes.forEach(function (mesh, index, array) {
  25834. var boundingInfo = mesh.getBoundingInfo();
  25835. var boundingBox = boundingInfo.boundingBox;
  25836. if (!minVector || !maxVector) {
  25837. minVector = boundingBox.minimumWorld;
  25838. maxVector = boundingBox.maximumWorld;
  25839. }
  25840. else {
  25841. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25842. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25843. }
  25844. });
  25845. if (!minVector || !maxVector) {
  25846. return {
  25847. min: BABYLON.Vector3.Zero(),
  25848. max: BABYLON.Vector3.Zero()
  25849. };
  25850. }
  25851. return {
  25852. min: minVector,
  25853. max: maxVector
  25854. };
  25855. };
  25856. /**
  25857. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25858. */
  25859. Mesh.Center = function (meshesOrMinMaxVector) {
  25860. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25861. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25862. };
  25863. /**
  25864. * Merge the array of meshes into a single mesh for performance reasons.
  25865. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25866. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25867. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25868. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25869. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25870. */
  25871. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25872. if (disposeSource === void 0) { disposeSource = true; }
  25873. var index;
  25874. if (!allow32BitsIndices) {
  25875. var totalVertices = 0;
  25876. // Counting vertices
  25877. for (index = 0; index < meshes.length; index++) {
  25878. if (meshes[index]) {
  25879. totalVertices += meshes[index].getTotalVertices();
  25880. if (totalVertices > 65536) {
  25881. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25882. return null;
  25883. }
  25884. }
  25885. }
  25886. }
  25887. // Merge
  25888. var vertexData = null;
  25889. var otherVertexData;
  25890. var indiceArray = new Array();
  25891. var source = null;
  25892. for (index = 0; index < meshes.length; index++) {
  25893. if (meshes[index]) {
  25894. meshes[index].computeWorldMatrix(true);
  25895. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25896. otherVertexData.transform(meshes[index].getWorldMatrix());
  25897. if (vertexData) {
  25898. vertexData.merge(otherVertexData);
  25899. }
  25900. else {
  25901. vertexData = otherVertexData;
  25902. source = meshes[index];
  25903. }
  25904. if (subdivideWithSubMeshes) {
  25905. indiceArray.push(meshes[index].getTotalIndices());
  25906. }
  25907. }
  25908. }
  25909. source = source;
  25910. if (!meshSubclass) {
  25911. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25912. }
  25913. vertexData.applyToMesh(meshSubclass);
  25914. // Setting properties
  25915. meshSubclass.material = source.material;
  25916. meshSubclass.checkCollisions = source.checkCollisions;
  25917. // Cleaning
  25918. if (disposeSource) {
  25919. for (index = 0; index < meshes.length; index++) {
  25920. if (meshes[index]) {
  25921. meshes[index].dispose();
  25922. }
  25923. }
  25924. }
  25925. // Subdivide
  25926. if (subdivideWithSubMeshes) {
  25927. //-- Suppresions du submesh global
  25928. meshSubclass.releaseSubMeshes();
  25929. index = 0;
  25930. var offset = 0;
  25931. //-- aplique la subdivision en fonction du tableau d'indices
  25932. while (index < indiceArray.length) {
  25933. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25934. offset += indiceArray[index];
  25935. index++;
  25936. }
  25937. }
  25938. return meshSubclass;
  25939. };
  25940. // Consts
  25941. Mesh._FRONTSIDE = 0;
  25942. Mesh._BACKSIDE = 1;
  25943. Mesh._DOUBLESIDE = 2;
  25944. Mesh._DEFAULTSIDE = 0;
  25945. Mesh._NO_CAP = 0;
  25946. Mesh._CAP_START = 1;
  25947. Mesh._CAP_END = 2;
  25948. Mesh._CAP_ALL = 3;
  25949. return Mesh;
  25950. }(BABYLON.AbstractMesh));
  25951. BABYLON.Mesh = Mesh;
  25952. })(BABYLON || (BABYLON = {}));
  25953. //# sourceMappingURL=babylon.mesh.js.map
  25954. var BABYLON;
  25955. (function (BABYLON) {
  25956. var BaseSubMesh = /** @class */ (function () {
  25957. function BaseSubMesh() {
  25958. }
  25959. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25960. get: function () {
  25961. return this._materialEffect;
  25962. },
  25963. enumerable: true,
  25964. configurable: true
  25965. });
  25966. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25967. if (defines === void 0) { defines = null; }
  25968. if (this._materialEffect === effect) {
  25969. if (!effect) {
  25970. this._materialDefines = null;
  25971. }
  25972. return;
  25973. }
  25974. this._materialDefines = defines;
  25975. this._materialEffect = effect;
  25976. };
  25977. return BaseSubMesh;
  25978. }());
  25979. BABYLON.BaseSubMesh = BaseSubMesh;
  25980. var SubMesh = /** @class */ (function (_super) {
  25981. __extends(SubMesh, _super);
  25982. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25983. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25984. var _this = _super.call(this) || this;
  25985. _this.materialIndex = materialIndex;
  25986. _this.verticesStart = verticesStart;
  25987. _this.verticesCount = verticesCount;
  25988. _this.indexStart = indexStart;
  25989. _this.indexCount = indexCount;
  25990. _this._renderId = 0;
  25991. _this._mesh = mesh;
  25992. _this._renderingMesh = renderingMesh || mesh;
  25993. mesh.subMeshes.push(_this);
  25994. _this._trianglePlanes = [];
  25995. _this._id = mesh.subMeshes.length - 1;
  25996. if (createBoundingBox) {
  25997. _this.refreshBoundingInfo();
  25998. mesh.computeWorldMatrix(true);
  25999. }
  26000. return _this;
  26001. }
  26002. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26003. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26004. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26005. };
  26006. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26007. get: function () {
  26008. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26009. },
  26010. enumerable: true,
  26011. configurable: true
  26012. });
  26013. /**
  26014. * Returns the submesh BoudingInfo object.
  26015. */
  26016. SubMesh.prototype.getBoundingInfo = function () {
  26017. if (this.IsGlobal) {
  26018. return this._mesh.getBoundingInfo();
  26019. }
  26020. return this._boundingInfo;
  26021. };
  26022. /**
  26023. * Sets the submesh BoundingInfo.
  26024. * Return the SubMesh.
  26025. */
  26026. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26027. this._boundingInfo = boundingInfo;
  26028. return this;
  26029. };
  26030. /**
  26031. * Returns the mesh of the current submesh.
  26032. */
  26033. SubMesh.prototype.getMesh = function () {
  26034. return this._mesh;
  26035. };
  26036. /**
  26037. * Returns the rendering mesh of the submesh.
  26038. */
  26039. SubMesh.prototype.getRenderingMesh = function () {
  26040. return this._renderingMesh;
  26041. };
  26042. /**
  26043. * Returns the submesh material.
  26044. */
  26045. SubMesh.prototype.getMaterial = function () {
  26046. var rootMaterial = this._renderingMesh.material;
  26047. if (rootMaterial && rootMaterial.getSubMaterial) {
  26048. var multiMaterial = rootMaterial;
  26049. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26050. if (this._currentMaterial !== effectiveMaterial) {
  26051. this._currentMaterial = effectiveMaterial;
  26052. this._materialDefines = null;
  26053. }
  26054. return effectiveMaterial;
  26055. }
  26056. if (!rootMaterial) {
  26057. return this._mesh.getScene().defaultMaterial;
  26058. }
  26059. return rootMaterial;
  26060. };
  26061. // Methods
  26062. /**
  26063. * Sets a new updated BoundingInfo object to the submesh.
  26064. * Returns the SubMesh.
  26065. */
  26066. SubMesh.prototype.refreshBoundingInfo = function () {
  26067. this._lastColliderWorldVertices = null;
  26068. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26069. return this;
  26070. }
  26071. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26072. if (!data) {
  26073. this._boundingInfo = this._mesh.getBoundingInfo();
  26074. return this;
  26075. }
  26076. var indices = this._renderingMesh.getIndices();
  26077. var extend;
  26078. //is this the only submesh?
  26079. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26080. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26081. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26082. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26083. }
  26084. else {
  26085. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26086. }
  26087. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26088. return this;
  26089. };
  26090. SubMesh.prototype._checkCollision = function (collider) {
  26091. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26092. return boundingInfo._checkCollision(collider);
  26093. };
  26094. /**
  26095. * Updates the submesh BoundingInfo.
  26096. * Returns the Submesh.
  26097. */
  26098. SubMesh.prototype.updateBoundingInfo = function (world) {
  26099. var boundingInfo = this.getBoundingInfo();
  26100. if (!boundingInfo) {
  26101. this.refreshBoundingInfo();
  26102. boundingInfo = this.getBoundingInfo();
  26103. }
  26104. boundingInfo.update(world);
  26105. return this;
  26106. };
  26107. /**
  26108. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26109. * Boolean returned.
  26110. */
  26111. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26112. var boundingInfo = this.getBoundingInfo();
  26113. if (!boundingInfo) {
  26114. return false;
  26115. }
  26116. return boundingInfo.isInFrustum(frustumPlanes);
  26117. };
  26118. /**
  26119. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26120. * Boolean returned.
  26121. */
  26122. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26123. var boundingInfo = this.getBoundingInfo();
  26124. if (!boundingInfo) {
  26125. return false;
  26126. }
  26127. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26128. };
  26129. /**
  26130. * Renders the submesh.
  26131. * Returns it.
  26132. */
  26133. SubMesh.prototype.render = function (enableAlphaMode) {
  26134. this._renderingMesh.render(this, enableAlphaMode);
  26135. return this;
  26136. };
  26137. /**
  26138. * Returns a new Index Buffer.
  26139. * Type returned : WebGLBuffer.
  26140. */
  26141. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26142. if (!this._linesIndexBuffer) {
  26143. var linesIndices = [];
  26144. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26145. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26146. }
  26147. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26148. this.linesIndexCount = linesIndices.length;
  26149. }
  26150. return this._linesIndexBuffer;
  26151. };
  26152. /**
  26153. * True is the passed Ray intersects the submesh bounding box.
  26154. * Boolean returned.
  26155. */
  26156. SubMesh.prototype.canIntersects = function (ray) {
  26157. var boundingInfo = this.getBoundingInfo();
  26158. if (!boundingInfo) {
  26159. return false;
  26160. }
  26161. return ray.intersectsBox(boundingInfo.boundingBox);
  26162. };
  26163. /**
  26164. * Returns an object IntersectionInfo.
  26165. */
  26166. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26167. var intersectInfo = null;
  26168. // LineMesh first as it's also a Mesh...
  26169. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26170. var lineMesh = this._mesh;
  26171. // Line test
  26172. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26173. var p0 = positions[indices[index]];
  26174. var p1 = positions[indices[index + 1]];
  26175. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26176. if (length < 0) {
  26177. continue;
  26178. }
  26179. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26180. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26181. if (fastCheck) {
  26182. break;
  26183. }
  26184. }
  26185. }
  26186. }
  26187. else {
  26188. // Triangles test
  26189. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26190. var p0 = positions[indices[index]];
  26191. var p1 = positions[indices[index + 1]];
  26192. var p2 = positions[indices[index + 2]];
  26193. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26194. if (currentIntersectInfo) {
  26195. if (currentIntersectInfo.distance < 0) {
  26196. continue;
  26197. }
  26198. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26199. intersectInfo = currentIntersectInfo;
  26200. intersectInfo.faceId = index / 3;
  26201. if (fastCheck) {
  26202. break;
  26203. }
  26204. }
  26205. }
  26206. }
  26207. }
  26208. return intersectInfo;
  26209. };
  26210. SubMesh.prototype._rebuild = function () {
  26211. if (this._linesIndexBuffer) {
  26212. this._linesIndexBuffer = null;
  26213. }
  26214. };
  26215. // Clone
  26216. /**
  26217. * Creates a new Submesh from the passed Mesh.
  26218. */
  26219. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26220. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26221. if (!this.IsGlobal) {
  26222. var boundingInfo = this.getBoundingInfo();
  26223. if (!boundingInfo) {
  26224. return result;
  26225. }
  26226. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26227. }
  26228. return result;
  26229. };
  26230. // Dispose
  26231. /**
  26232. * Disposes the Submesh.
  26233. * Returns nothing.
  26234. */
  26235. SubMesh.prototype.dispose = function () {
  26236. if (this._linesIndexBuffer) {
  26237. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26238. this._linesIndexBuffer = null;
  26239. }
  26240. // Remove from mesh
  26241. var index = this._mesh.subMeshes.indexOf(this);
  26242. this._mesh.subMeshes.splice(index, 1);
  26243. };
  26244. // Statics
  26245. /**
  26246. * Creates a new Submesh from the passed parameters :
  26247. * - materialIndex (integer) : the index of the main mesh material.
  26248. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26249. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26250. * - mesh (Mesh) : the main mesh to create the submesh from.
  26251. * - renderingMesh (optional Mesh) : rendering mesh.
  26252. */
  26253. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26254. var minVertexIndex = Number.MAX_VALUE;
  26255. var maxVertexIndex = -Number.MAX_VALUE;
  26256. renderingMesh = (renderingMesh || mesh);
  26257. var indices = renderingMesh.getIndices();
  26258. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26259. var vertexIndex = indices[index];
  26260. if (vertexIndex < minVertexIndex)
  26261. minVertexIndex = vertexIndex;
  26262. if (vertexIndex > maxVertexIndex)
  26263. maxVertexIndex = vertexIndex;
  26264. }
  26265. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26266. };
  26267. return SubMesh;
  26268. }(BaseSubMesh));
  26269. BABYLON.SubMesh = SubMesh;
  26270. })(BABYLON || (BABYLON = {}));
  26271. //# sourceMappingURL=babylon.subMesh.js.map
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. var EffectFallbacks = /** @class */ (function () {
  26275. function EffectFallbacks() {
  26276. this._defines = {};
  26277. this._currentRank = 32;
  26278. this._maxRank = -1;
  26279. }
  26280. EffectFallbacks.prototype.unBindMesh = function () {
  26281. this._mesh = null;
  26282. };
  26283. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26284. if (!this._defines[rank]) {
  26285. if (rank < this._currentRank) {
  26286. this._currentRank = rank;
  26287. }
  26288. if (rank > this._maxRank) {
  26289. this._maxRank = rank;
  26290. }
  26291. this._defines[rank] = new Array();
  26292. }
  26293. this._defines[rank].push(define);
  26294. };
  26295. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26296. this._mesh = mesh;
  26297. if (rank < this._currentRank) {
  26298. this._currentRank = rank;
  26299. }
  26300. if (rank > this._maxRank) {
  26301. this._maxRank = rank;
  26302. }
  26303. };
  26304. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26305. get: function () {
  26306. return this._currentRank <= this._maxRank;
  26307. },
  26308. enumerable: true,
  26309. configurable: true
  26310. });
  26311. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26312. // First we try to switch to CPU skinning
  26313. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26314. this._mesh.computeBonesUsingShaders = false;
  26315. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26316. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26317. var scene = this._mesh.getScene();
  26318. for (var index = 0; index < scene.meshes.length; index++) {
  26319. var otherMesh = scene.meshes[index];
  26320. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26321. otherMesh.computeBonesUsingShaders = false;
  26322. }
  26323. }
  26324. }
  26325. else {
  26326. var currentFallbacks = this._defines[this._currentRank];
  26327. if (currentFallbacks) {
  26328. for (var index = 0; index < currentFallbacks.length; index++) {
  26329. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26330. }
  26331. }
  26332. this._currentRank++;
  26333. }
  26334. return currentDefines;
  26335. };
  26336. return EffectFallbacks;
  26337. }());
  26338. BABYLON.EffectFallbacks = EffectFallbacks;
  26339. var EffectCreationOptions = /** @class */ (function () {
  26340. function EffectCreationOptions() {
  26341. }
  26342. return EffectCreationOptions;
  26343. }());
  26344. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26345. var Effect = /** @class */ (function () {
  26346. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26347. if (samplers === void 0) { samplers = null; }
  26348. if (defines === void 0) { defines = null; }
  26349. if (fallbacks === void 0) { fallbacks = null; }
  26350. if (onCompiled === void 0) { onCompiled = null; }
  26351. if (onError === void 0) { onError = null; }
  26352. var _this = this;
  26353. this.uniqueId = 0;
  26354. this.onCompileObservable = new BABYLON.Observable();
  26355. this.onErrorObservable = new BABYLON.Observable();
  26356. this.onBindObservable = new BABYLON.Observable();
  26357. this._uniformBuffersNames = {};
  26358. this._isReady = false;
  26359. this._compilationError = "";
  26360. this.name = baseName;
  26361. if (attributesNamesOrOptions.attributes) {
  26362. var options = attributesNamesOrOptions;
  26363. this._engine = uniformsNamesOrEngine;
  26364. this._attributesNames = options.attributes;
  26365. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26366. this._samplers = options.samplers;
  26367. this.defines = options.defines;
  26368. this.onError = options.onError;
  26369. this.onCompiled = options.onCompiled;
  26370. this._fallbacks = options.fallbacks;
  26371. this._indexParameters = options.indexParameters;
  26372. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26373. if (options.uniformBuffersNames) {
  26374. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26375. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26376. }
  26377. }
  26378. }
  26379. else {
  26380. this._engine = engine;
  26381. this.defines = defines;
  26382. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26383. this._samplers = samplers;
  26384. this._attributesNames = attributesNamesOrOptions;
  26385. this.onError = onError;
  26386. this.onCompiled = onCompiled;
  26387. this._indexParameters = indexParameters;
  26388. this._fallbacks = fallbacks;
  26389. }
  26390. this.uniqueId = Effect._uniqueIdSeed++;
  26391. var vertexSource;
  26392. var fragmentSource;
  26393. if (baseName.vertexElement) {
  26394. vertexSource = document.getElementById(baseName.vertexElement);
  26395. if (!vertexSource) {
  26396. vertexSource = baseName.vertexElement;
  26397. }
  26398. }
  26399. else {
  26400. vertexSource = baseName.vertex || baseName;
  26401. }
  26402. if (baseName.fragmentElement) {
  26403. fragmentSource = document.getElementById(baseName.fragmentElement);
  26404. if (!fragmentSource) {
  26405. fragmentSource = baseName.fragmentElement;
  26406. }
  26407. }
  26408. else {
  26409. fragmentSource = baseName.fragment || baseName;
  26410. }
  26411. this._loadVertexShader(vertexSource, function (vertexCode) {
  26412. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26413. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26414. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26415. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26416. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26417. if (baseName) {
  26418. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26419. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26420. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26421. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26422. }
  26423. else {
  26424. _this._vertexSourceCode = migratedVertexCode;
  26425. _this._fragmentSourceCode = migratedFragmentCode;
  26426. }
  26427. _this._prepareEffect();
  26428. });
  26429. });
  26430. });
  26431. });
  26432. });
  26433. });
  26434. }
  26435. Object.defineProperty(Effect.prototype, "key", {
  26436. get: function () {
  26437. return this._key;
  26438. },
  26439. enumerable: true,
  26440. configurable: true
  26441. });
  26442. // Properties
  26443. Effect.prototype.isReady = function () {
  26444. return this._isReady;
  26445. };
  26446. Effect.prototype.getEngine = function () {
  26447. return this._engine;
  26448. };
  26449. Effect.prototype.getProgram = function () {
  26450. return this._program;
  26451. };
  26452. Effect.prototype.getAttributesNames = function () {
  26453. return this._attributesNames;
  26454. };
  26455. Effect.prototype.getAttributeLocation = function (index) {
  26456. return this._attributes[index];
  26457. };
  26458. Effect.prototype.getAttributeLocationByName = function (name) {
  26459. var index = this._attributesNames.indexOf(name);
  26460. return this._attributes[index];
  26461. };
  26462. Effect.prototype.getAttributesCount = function () {
  26463. return this._attributes.length;
  26464. };
  26465. Effect.prototype.getUniformIndex = function (uniformName) {
  26466. return this._uniformsNames.indexOf(uniformName);
  26467. };
  26468. Effect.prototype.getUniform = function (uniformName) {
  26469. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26470. };
  26471. Effect.prototype.getSamplers = function () {
  26472. return this._samplers;
  26473. };
  26474. Effect.prototype.getCompilationError = function () {
  26475. return this._compilationError;
  26476. };
  26477. // Methods
  26478. Effect.prototype.executeWhenCompiled = function (func) {
  26479. if (this.isReady()) {
  26480. func(this);
  26481. return;
  26482. }
  26483. this.onCompileObservable.add(function (effect) {
  26484. func(effect);
  26485. });
  26486. };
  26487. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26488. if (BABYLON.Tools.IsWindowObjectExist()) {
  26489. // DOM element ?
  26490. if (vertex instanceof HTMLElement) {
  26491. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26492. callback(vertexCode);
  26493. return;
  26494. }
  26495. }
  26496. // Base64 encoded ?
  26497. if (vertex.substr(0, 7) === "base64:") {
  26498. var vertexBinary = window.atob(vertex.substr(7));
  26499. callback(vertexBinary);
  26500. return;
  26501. }
  26502. // Is in local store ?
  26503. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26504. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26505. return;
  26506. }
  26507. var vertexShaderUrl;
  26508. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26509. vertexShaderUrl = vertex;
  26510. }
  26511. else {
  26512. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26513. }
  26514. // Vertex shader
  26515. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26516. };
  26517. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26518. if (BABYLON.Tools.IsWindowObjectExist()) {
  26519. // DOM element ?
  26520. if (fragment instanceof HTMLElement) {
  26521. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26522. callback(fragmentCode);
  26523. return;
  26524. }
  26525. }
  26526. // Base64 encoded ?
  26527. if (fragment.substr(0, 7) === "base64:") {
  26528. var fragmentBinary = window.atob(fragment.substr(7));
  26529. callback(fragmentBinary);
  26530. return;
  26531. }
  26532. // Is in local store ?
  26533. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26534. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26535. return;
  26536. }
  26537. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26538. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26539. return;
  26540. }
  26541. var fragmentShaderUrl;
  26542. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26543. fragmentShaderUrl = fragment;
  26544. }
  26545. else {
  26546. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26547. }
  26548. // Fragment shader
  26549. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26550. };
  26551. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26552. // Rebuild shaders source code
  26553. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26554. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26555. vertexCode = prefix + vertexCode;
  26556. fragmentCode = prefix + fragmentCode;
  26557. // Number lines of shaders source code
  26558. var i = 2;
  26559. var regex = /\n/gm;
  26560. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26561. i = 2;
  26562. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26563. // Dump shaders name and formatted source code
  26564. if (this.name.vertexElement) {
  26565. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26566. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26567. }
  26568. else if (this.name.vertex) {
  26569. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26570. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26571. }
  26572. else {
  26573. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26574. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26575. }
  26576. };
  26577. ;
  26578. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26579. var preparedSourceCode = this._processPrecision(sourceCode);
  26580. if (this._engine.webGLVersion == 1) {
  26581. callback(preparedSourceCode);
  26582. return;
  26583. }
  26584. // Already converted
  26585. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26586. callback(preparedSourceCode.replace("#version 300 es", ""));
  26587. return;
  26588. }
  26589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26590. // Remove extensions
  26591. // #extension GL_OES_standard_derivatives : enable
  26592. // #extension GL_EXT_shader_texture_lod : enable
  26593. // #extension GL_EXT_frag_depth : enable
  26594. // #extension GL_EXT_draw_buffers : require
  26595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26596. var result = preparedSourceCode.replace(regex, "");
  26597. // Migrate to GLSL v300
  26598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26599. result = result.replace(/attribute[ \t]/g, "in ");
  26600. result = result.replace(/[ \t]attribute/g, " in");
  26601. if (isFragment) {
  26602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26604. result = result.replace(/texture2D\s*\(/g, "texture(");
  26605. result = result.replace(/textureCube\s*\(/g, "texture(");
  26606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26607. result = result.replace(/gl_FragColor/g, "glFragColor");
  26608. result = result.replace(/gl_FragData/g, "glFragData");
  26609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26610. }
  26611. callback(result);
  26612. };
  26613. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26614. var _this = this;
  26615. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26616. var match = regex.exec(sourceCode);
  26617. var returnValue = new String(sourceCode);
  26618. while (match != null) {
  26619. var includeFile = match[1];
  26620. // Uniform declaration
  26621. if (includeFile.indexOf("__decl__") !== -1) {
  26622. includeFile = includeFile.replace(/__decl__/, "");
  26623. if (this._engine.supportsUniformBuffers) {
  26624. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26625. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26626. }
  26627. includeFile = includeFile + "Declaration";
  26628. }
  26629. if (Effect.IncludesShadersStore[includeFile]) {
  26630. // Substitution
  26631. var includeContent = Effect.IncludesShadersStore[includeFile];
  26632. if (match[2]) {
  26633. var splits = match[3].split(",");
  26634. for (var index = 0; index < splits.length; index += 2) {
  26635. var source = new RegExp(splits[index], "g");
  26636. var dest = splits[index + 1];
  26637. includeContent = includeContent.replace(source, dest);
  26638. }
  26639. }
  26640. if (match[4]) {
  26641. var indexString = match[5];
  26642. if (indexString.indexOf("..") !== -1) {
  26643. var indexSplits = indexString.split("..");
  26644. var minIndex = parseInt(indexSplits[0]);
  26645. var maxIndex = parseInt(indexSplits[1]);
  26646. var sourceIncludeContent = includeContent.slice(0);
  26647. includeContent = "";
  26648. if (isNaN(maxIndex)) {
  26649. maxIndex = this._indexParameters[indexSplits[1]];
  26650. }
  26651. for (var i = minIndex; i < maxIndex; i++) {
  26652. if (!this._engine.supportsUniformBuffers) {
  26653. // Ubo replacement
  26654. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26655. return p1 + "{X}";
  26656. });
  26657. }
  26658. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26659. }
  26660. }
  26661. else {
  26662. if (!this._engine.supportsUniformBuffers) {
  26663. // Ubo replacement
  26664. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26665. return p1 + "{X}";
  26666. });
  26667. }
  26668. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26669. }
  26670. }
  26671. // Replace
  26672. returnValue = returnValue.replace(match[0], includeContent);
  26673. }
  26674. else {
  26675. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26676. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26677. Effect.IncludesShadersStore[includeFile] = fileContent;
  26678. _this._processIncludes(returnValue, callback);
  26679. });
  26680. return;
  26681. }
  26682. match = regex.exec(sourceCode);
  26683. }
  26684. callback(returnValue);
  26685. };
  26686. Effect.prototype._processPrecision = function (source) {
  26687. if (source.indexOf("precision highp float") === -1) {
  26688. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26689. source = "precision mediump float;\n" + source;
  26690. }
  26691. else {
  26692. source = "precision highp float;\n" + source;
  26693. }
  26694. }
  26695. else {
  26696. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26697. source = source.replace("precision highp float", "precision mediump float");
  26698. }
  26699. }
  26700. return source;
  26701. };
  26702. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26703. var _this = this;
  26704. this._isReady = false;
  26705. this._vertexSourceCodeOverride = vertexSourceCode;
  26706. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26707. this.onError = function (effect, error) {
  26708. if (onError) {
  26709. onError(error);
  26710. }
  26711. };
  26712. this.onCompiled = function () {
  26713. var scenes = _this.getEngine().scenes;
  26714. for (var i = 0; i < scenes.length; i++) {
  26715. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26716. }
  26717. if (onCompiled) {
  26718. onCompiled(_this._program);
  26719. }
  26720. };
  26721. this._fallbacks = null;
  26722. this._prepareEffect();
  26723. };
  26724. Effect.prototype._prepareEffect = function () {
  26725. var attributesNames = this._attributesNames;
  26726. var defines = this.defines;
  26727. var fallbacks = this._fallbacks;
  26728. this._valueCache = {};
  26729. var previousProgram = this._program;
  26730. try {
  26731. var engine = this._engine;
  26732. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26733. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26734. }
  26735. else {
  26736. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26737. }
  26738. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26739. if (engine.webGLVersion > 1) {
  26740. for (var name in this._uniformBuffersNames) {
  26741. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26742. }
  26743. }
  26744. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26745. this._attributes = engine.getAttributes(this._program, attributesNames);
  26746. var index;
  26747. for (index = 0; index < this._samplers.length; index++) {
  26748. var sampler = this.getUniform(this._samplers[index]);
  26749. if (sampler == null) {
  26750. this._samplers.splice(index, 1);
  26751. index--;
  26752. }
  26753. }
  26754. engine.bindSamplers(this);
  26755. this._compilationError = "";
  26756. this._isReady = true;
  26757. if (this.onCompiled) {
  26758. this.onCompiled(this);
  26759. }
  26760. this.onCompileObservable.notifyObservers(this);
  26761. this.onCompileObservable.clear();
  26762. // Unbind mesh reference in fallbacks
  26763. if (this._fallbacks) {
  26764. this._fallbacks.unBindMesh();
  26765. }
  26766. if (previousProgram) {
  26767. this.getEngine()._deleteProgram(previousProgram);
  26768. }
  26769. }
  26770. catch (e) {
  26771. this._compilationError = e.message;
  26772. // Let's go through fallbacks then
  26773. BABYLON.Tools.Error("Unable to compile effect:");
  26774. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26775. return " " + uniform;
  26776. }));
  26777. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26778. return " " + attribute;
  26779. }));
  26780. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26781. BABYLON.Tools.Error("Error: " + this._compilationError);
  26782. if (previousProgram) {
  26783. this._program = previousProgram;
  26784. this._isReady = true;
  26785. if (this.onError) {
  26786. this.onError(this, this._compilationError);
  26787. }
  26788. this.onErrorObservable.notifyObservers(this);
  26789. }
  26790. if (fallbacks && fallbacks.isMoreFallbacks) {
  26791. BABYLON.Tools.Error("Trying next fallback.");
  26792. this.defines = fallbacks.reduce(this.defines);
  26793. this._prepareEffect();
  26794. }
  26795. else {
  26796. if (this.onError) {
  26797. this.onError(this, this._compilationError);
  26798. }
  26799. this.onErrorObservable.notifyObservers(this);
  26800. this.onErrorObservable.clear();
  26801. // Unbind mesh reference in fallbacks
  26802. if (this._fallbacks) {
  26803. this._fallbacks.unBindMesh();
  26804. }
  26805. }
  26806. }
  26807. };
  26808. Object.defineProperty(Effect.prototype, "isSupported", {
  26809. get: function () {
  26810. return this._compilationError === "";
  26811. },
  26812. enumerable: true,
  26813. configurable: true
  26814. });
  26815. Effect.prototype._bindTexture = function (channel, texture) {
  26816. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26817. };
  26818. Effect.prototype.setTexture = function (channel, texture) {
  26819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26820. };
  26821. Effect.prototype.setTextureArray = function (channel, textures) {
  26822. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26823. var initialPos = this._samplers.indexOf(channel);
  26824. for (var index = 1; index < textures.length; index++) {
  26825. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26826. }
  26827. }
  26828. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26829. };
  26830. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26831. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26832. };
  26833. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26834. var cache = this._valueCache[uniformName];
  26835. var flag = matrix.updateFlag;
  26836. if (cache !== undefined && cache === flag) {
  26837. return false;
  26838. }
  26839. this._valueCache[uniformName] = flag;
  26840. return true;
  26841. };
  26842. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26843. var cache = this._valueCache[uniformName];
  26844. if (!cache) {
  26845. cache = [x, y];
  26846. this._valueCache[uniformName] = cache;
  26847. return true;
  26848. }
  26849. var changed = false;
  26850. if (cache[0] !== x) {
  26851. cache[0] = x;
  26852. changed = true;
  26853. }
  26854. if (cache[1] !== y) {
  26855. cache[1] = y;
  26856. changed = true;
  26857. }
  26858. return changed;
  26859. };
  26860. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26861. var cache = this._valueCache[uniformName];
  26862. if (!cache) {
  26863. cache = [x, y, z];
  26864. this._valueCache[uniformName] = cache;
  26865. return true;
  26866. }
  26867. var changed = false;
  26868. if (cache[0] !== x) {
  26869. cache[0] = x;
  26870. changed = true;
  26871. }
  26872. if (cache[1] !== y) {
  26873. cache[1] = y;
  26874. changed = true;
  26875. }
  26876. if (cache[2] !== z) {
  26877. cache[2] = z;
  26878. changed = true;
  26879. }
  26880. return changed;
  26881. };
  26882. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26883. var cache = this._valueCache[uniformName];
  26884. if (!cache) {
  26885. cache = [x, y, z, w];
  26886. this._valueCache[uniformName] = cache;
  26887. return true;
  26888. }
  26889. var changed = false;
  26890. if (cache[0] !== x) {
  26891. cache[0] = x;
  26892. changed = true;
  26893. }
  26894. if (cache[1] !== y) {
  26895. cache[1] = y;
  26896. changed = true;
  26897. }
  26898. if (cache[2] !== z) {
  26899. cache[2] = z;
  26900. changed = true;
  26901. }
  26902. if (cache[3] !== w) {
  26903. cache[3] = w;
  26904. changed = true;
  26905. }
  26906. return changed;
  26907. };
  26908. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26909. var bufferName = this._uniformBuffersNames[name];
  26910. if (Effect._baseCache[bufferName] === buffer) {
  26911. return;
  26912. }
  26913. Effect._baseCache[bufferName] = buffer;
  26914. this._engine.bindUniformBufferBase(buffer, bufferName);
  26915. };
  26916. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26917. this._engine.bindUniformBlock(this._program, blockName, index);
  26918. };
  26919. Effect.prototype.setIntArray = function (uniformName, array) {
  26920. this._valueCache[uniformName] = null;
  26921. this._engine.setIntArray(this.getUniform(uniformName), array);
  26922. return this;
  26923. };
  26924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26925. this._valueCache[uniformName] = null;
  26926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26927. return this;
  26928. };
  26929. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26930. this._valueCache[uniformName] = null;
  26931. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26932. return this;
  26933. };
  26934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26935. this._valueCache[uniformName] = null;
  26936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26937. return this;
  26938. };
  26939. Effect.prototype.setFloatArray = function (uniformName, array) {
  26940. this._valueCache[uniformName] = null;
  26941. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26942. return this;
  26943. };
  26944. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26945. this._valueCache[uniformName] = null;
  26946. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26947. return this;
  26948. };
  26949. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26950. this._valueCache[uniformName] = null;
  26951. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26952. return this;
  26953. };
  26954. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26955. this._valueCache[uniformName] = null;
  26956. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26957. return this;
  26958. };
  26959. Effect.prototype.setArray = function (uniformName, array) {
  26960. this._valueCache[uniformName] = null;
  26961. this._engine.setArray(this.getUniform(uniformName), array);
  26962. return this;
  26963. };
  26964. Effect.prototype.setArray2 = function (uniformName, array) {
  26965. this._valueCache[uniformName] = null;
  26966. this._engine.setArray2(this.getUniform(uniformName), array);
  26967. return this;
  26968. };
  26969. Effect.prototype.setArray3 = function (uniformName, array) {
  26970. this._valueCache[uniformName] = null;
  26971. this._engine.setArray3(this.getUniform(uniformName), array);
  26972. return this;
  26973. };
  26974. Effect.prototype.setArray4 = function (uniformName, array) {
  26975. this._valueCache[uniformName] = null;
  26976. this._engine.setArray4(this.getUniform(uniformName), array);
  26977. return this;
  26978. };
  26979. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26980. if (!matrices) {
  26981. return this;
  26982. }
  26983. this._valueCache[uniformName] = null;
  26984. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26985. return this;
  26986. };
  26987. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26988. if (this._cacheMatrix(uniformName, matrix)) {
  26989. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26990. }
  26991. return this;
  26992. };
  26993. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26994. this._valueCache[uniformName] = null;
  26995. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26996. return this;
  26997. };
  26998. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26999. this._valueCache[uniformName] = null;
  27000. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27001. return this;
  27002. };
  27003. Effect.prototype.setFloat = function (uniformName, value) {
  27004. var cache = this._valueCache[uniformName];
  27005. if (cache !== undefined && cache === value)
  27006. return this;
  27007. this._valueCache[uniformName] = value;
  27008. this._engine.setFloat(this.getUniform(uniformName), value);
  27009. return this;
  27010. };
  27011. Effect.prototype.setBool = function (uniformName, bool) {
  27012. var cache = this._valueCache[uniformName];
  27013. if (cache !== undefined && cache === bool)
  27014. return this;
  27015. this._valueCache[uniformName] = bool;
  27016. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27017. return this;
  27018. };
  27019. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27020. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27021. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27022. }
  27023. return this;
  27024. };
  27025. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27026. if (this._cacheFloat2(uniformName, x, y)) {
  27027. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27028. }
  27029. return this;
  27030. };
  27031. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27032. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27033. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27034. }
  27035. return this;
  27036. };
  27037. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27038. if (this._cacheFloat3(uniformName, x, y, z)) {
  27039. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27040. }
  27041. return this;
  27042. };
  27043. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27044. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27045. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27046. }
  27047. return this;
  27048. };
  27049. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27050. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27051. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27052. }
  27053. return this;
  27054. };
  27055. Effect.prototype.setColor3 = function (uniformName, color3) {
  27056. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27057. this._engine.setColor3(this.getUniform(uniformName), color3);
  27058. }
  27059. return this;
  27060. };
  27061. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27062. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27063. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27064. }
  27065. return this;
  27066. };
  27067. Effect.ResetCache = function () {
  27068. Effect._baseCache = {};
  27069. };
  27070. Effect._uniqueIdSeed = 0;
  27071. Effect._baseCache = {};
  27072. // Statics
  27073. Effect.ShadersStore = {};
  27074. Effect.IncludesShadersStore = {};
  27075. return Effect;
  27076. }());
  27077. BABYLON.Effect = Effect;
  27078. })(BABYLON || (BABYLON = {}));
  27079. //# sourceMappingURL=babylon.effect.js.map
  27080. var BABYLON;
  27081. (function (BABYLON) {
  27082. var MaterialHelper = /** @class */ (function () {
  27083. function MaterialHelper() {
  27084. }
  27085. MaterialHelper.BindEyePosition = function (effect, scene) {
  27086. if (scene._forcedViewPosition) {
  27087. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  27088. return;
  27089. }
  27090. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  27091. };
  27092. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  27093. defines._needUVs = true;
  27094. defines[key] = true;
  27095. if (texture.getTextureMatrix().isIdentity(true)) {
  27096. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  27097. if (texture.coordinatesIndex === 0) {
  27098. defines["MAINUV1"] = true;
  27099. }
  27100. else {
  27101. defines["MAINUV2"] = true;
  27102. }
  27103. }
  27104. else {
  27105. defines[key + "DIRECTUV"] = 0;
  27106. }
  27107. };
  27108. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  27109. var matrix = texture.getTextureMatrix();
  27110. if (!matrix.isIdentity(true)) {
  27111. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  27112. }
  27113. };
  27114. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  27115. if (defines._areMiscDirty) {
  27116. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  27117. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  27118. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  27119. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  27120. }
  27121. };
  27122. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  27123. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  27124. var changed = false;
  27125. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  27126. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  27127. changed = true;
  27128. }
  27129. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  27130. defines["ALPHATEST"] = !defines["ALPHATEST"];
  27131. changed = true;
  27132. }
  27133. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  27134. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  27135. changed = true;
  27136. }
  27137. if (defines["INSTANCES"] !== useInstances) {
  27138. defines["INSTANCES"] = useInstances;
  27139. changed = true;
  27140. }
  27141. if (changed) {
  27142. defines.markAsUnprocessed();
  27143. }
  27144. };
  27145. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  27146. if (useMorphTargets === void 0) { useMorphTargets = false; }
  27147. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  27148. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  27149. return false;
  27150. }
  27151. defines._normals = defines._needNormals;
  27152. defines._uvs = defines._needUVs;
  27153. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  27154. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27155. defines["TANGENT"] = true;
  27156. }
  27157. if (defines._needUVs) {
  27158. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  27159. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  27160. }
  27161. else {
  27162. defines["UV1"] = false;
  27163. defines["UV2"] = false;
  27164. }
  27165. if (useVertexColor) {
  27166. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  27167. defines["VERTEXCOLOR"] = hasVertexColors;
  27168. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  27169. }
  27170. if (useBones) {
  27171. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27172. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  27173. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  27174. }
  27175. else {
  27176. defines["NUM_BONE_INFLUENCERS"] = 0;
  27177. defines["BonesPerMesh"] = 0;
  27178. }
  27179. }
  27180. if (useMorphTargets) {
  27181. var manager = mesh.morphTargetManager;
  27182. if (manager) {
  27183. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27184. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27185. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27186. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27187. }
  27188. else {
  27189. defines["MORPHTARGETS_TANGENT"] = false;
  27190. defines["MORPHTARGETS_NORMAL"] = false;
  27191. defines["MORPHTARGETS"] = false;
  27192. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27193. }
  27194. }
  27195. return true;
  27196. };
  27197. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27198. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27199. if (disableLighting === void 0) { disableLighting = false; }
  27200. if (!defines._areLightsDirty) {
  27201. return defines._needNormals;
  27202. }
  27203. var lightIndex = 0;
  27204. var needNormals = false;
  27205. var needRebuild = false;
  27206. var lightmapMode = false;
  27207. var shadowEnabled = false;
  27208. var specularEnabled = false;
  27209. if (scene.lightsEnabled && !disableLighting) {
  27210. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27211. var light = _a[_i];
  27212. needNormals = true;
  27213. if (defines["LIGHT" + lightIndex] === undefined) {
  27214. needRebuild = true;
  27215. }
  27216. defines["LIGHT" + lightIndex] = true;
  27217. defines["SPOTLIGHT" + lightIndex] = false;
  27218. defines["HEMILIGHT" + lightIndex] = false;
  27219. defines["POINTLIGHT" + lightIndex] = false;
  27220. defines["DIRLIGHT" + lightIndex] = false;
  27221. var type;
  27222. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27223. type = "SPOTLIGHT" + lightIndex;
  27224. }
  27225. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27226. type = "HEMILIGHT" + lightIndex;
  27227. }
  27228. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27229. type = "POINTLIGHT" + lightIndex;
  27230. }
  27231. else {
  27232. type = "DIRLIGHT" + lightIndex;
  27233. }
  27234. defines[type] = true;
  27235. // Specular
  27236. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27237. specularEnabled = true;
  27238. }
  27239. // Shadows
  27240. defines["SHADOW" + lightIndex] = false;
  27241. defines["SHADOWPCF" + lightIndex] = false;
  27242. defines["SHADOWESM" + lightIndex] = false;
  27243. defines["SHADOWCUBE" + lightIndex] = false;
  27244. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27245. var shadowGenerator = light.getShadowGenerator();
  27246. if (shadowGenerator) {
  27247. shadowEnabled = true;
  27248. shadowGenerator.prepareDefines(defines, lightIndex);
  27249. }
  27250. }
  27251. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27252. lightmapMode = true;
  27253. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27254. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27255. }
  27256. else {
  27257. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27258. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27259. }
  27260. lightIndex++;
  27261. if (lightIndex === maxSimultaneousLights)
  27262. break;
  27263. }
  27264. }
  27265. defines["SPECULARTERM"] = specularEnabled;
  27266. defines["SHADOWS"] = shadowEnabled;
  27267. // Resetting all other lights if any
  27268. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27269. if (defines["LIGHT" + index] !== undefined) {
  27270. defines["LIGHT" + index] = false;
  27271. defines["HEMILIGHT" + lightIndex] = false;
  27272. defines["POINTLIGHT" + lightIndex] = false;
  27273. defines["DIRLIGHT" + lightIndex] = false;
  27274. defines["SPOTLIGHT" + lightIndex] = false;
  27275. defines["SHADOW" + lightIndex] = false;
  27276. }
  27277. }
  27278. var caps = scene.getEngine().getCaps();
  27279. if (defines["SHADOWFLOAT"] === undefined) {
  27280. needRebuild = true;
  27281. }
  27282. defines["SHADOWFLOAT"] = shadowEnabled &&
  27283. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27284. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27285. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27286. if (needRebuild) {
  27287. defines.rebuild();
  27288. }
  27289. return needNormals;
  27290. };
  27291. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27292. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27293. var uniformsList;
  27294. var uniformBuffersList = null;
  27295. if (uniformsListOrOptions.uniformsNames) {
  27296. var options = uniformsListOrOptions;
  27297. uniformsList = options.uniformsNames;
  27298. uniformBuffersList = options.uniformBuffersNames;
  27299. samplersList = options.samplers;
  27300. defines = options.defines;
  27301. maxSimultaneousLights = options.maxSimultaneousLights;
  27302. }
  27303. else {
  27304. uniformsList = uniformsListOrOptions;
  27305. if (!samplersList) {
  27306. samplersList = [];
  27307. }
  27308. }
  27309. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27310. if (!defines["LIGHT" + lightIndex]) {
  27311. break;
  27312. }
  27313. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27314. if (uniformBuffersList) {
  27315. uniformBuffersList.push("Light" + lightIndex);
  27316. }
  27317. samplersList.push("shadowSampler" + lightIndex);
  27318. }
  27319. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27320. uniformsList.push("morphTargetInfluences");
  27321. }
  27322. };
  27323. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27324. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27325. if (rank === void 0) { rank = 0; }
  27326. var lightFallbackRank = 0;
  27327. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27328. if (!defines["LIGHT" + lightIndex]) {
  27329. break;
  27330. }
  27331. if (lightIndex > 0) {
  27332. lightFallbackRank = rank + lightIndex;
  27333. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27334. }
  27335. if (!defines["SHADOWS"]) {
  27336. if (defines["SHADOW" + lightIndex]) {
  27337. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27338. }
  27339. if (defines["SHADOWPCF" + lightIndex]) {
  27340. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27341. }
  27342. if (defines["SHADOWESM" + lightIndex]) {
  27343. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27344. }
  27345. }
  27346. }
  27347. return lightFallbackRank++;
  27348. };
  27349. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27350. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27351. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27352. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27353. var manager = mesh.morphTargetManager;
  27354. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27355. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27356. for (var index = 0; index < influencers; index++) {
  27357. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27358. if (normal) {
  27359. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27360. }
  27361. if (tangent) {
  27362. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27363. }
  27364. if (attribs.length > maxAttributesCount) {
  27365. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27366. }
  27367. }
  27368. }
  27369. };
  27370. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27371. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27372. fallbacks.addCPUSkinningFallback(0, mesh);
  27373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27375. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27378. }
  27379. }
  27380. };
  27381. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27382. if (defines["INSTANCES"]) {
  27383. attribs.push("world0");
  27384. attribs.push("world1");
  27385. attribs.push("world2");
  27386. attribs.push("world3");
  27387. }
  27388. };
  27389. // Bindings
  27390. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27391. if (light.shadowEnabled && mesh.receiveShadows) {
  27392. var shadowGenerator = light.getShadowGenerator();
  27393. if (shadowGenerator) {
  27394. shadowGenerator.bindShadowLight(lightIndex, effect);
  27395. }
  27396. }
  27397. };
  27398. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27399. light.transferToEffect(effect, lightIndex + "");
  27400. };
  27401. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27402. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27403. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27404. var lightIndex = 0;
  27405. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27406. var light = _a[_i];
  27407. var scaledIntensity = light.getScaledIntensity();
  27408. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27409. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27410. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27411. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27412. if (defines["SPECULARTERM"]) {
  27413. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27414. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27415. }
  27416. // Shadows
  27417. if (scene.shadowsEnabled) {
  27418. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27419. }
  27420. light._uniformBuffer.update();
  27421. lightIndex++;
  27422. if (lightIndex === maxSimultaneousLights)
  27423. break;
  27424. }
  27425. };
  27426. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27427. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27428. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27429. effect.setColor3("vFogColor", scene.fogColor);
  27430. }
  27431. };
  27432. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27433. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27434. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27435. if (matrices && effect) {
  27436. effect.setMatrices("mBones", matrices);
  27437. }
  27438. }
  27439. };
  27440. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27441. var manager = abstractMesh.morphTargetManager;
  27442. if (!abstractMesh || !manager) {
  27443. return;
  27444. }
  27445. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27446. };
  27447. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27448. if (defines["LOGARITHMICDEPTH"]) {
  27449. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27450. }
  27451. };
  27452. MaterialHelper.BindClipPlane = function (effect, scene) {
  27453. if (scene.clipPlane) {
  27454. var clipPlane = scene.clipPlane;
  27455. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27456. }
  27457. };
  27458. return MaterialHelper;
  27459. }());
  27460. BABYLON.MaterialHelper = MaterialHelper;
  27461. })(BABYLON || (BABYLON = {}));
  27462. //# sourceMappingURL=babylon.materialHelper.js.map
  27463. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27464. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27465. s = arguments[i];
  27466. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27467. t[p] = s[p];
  27468. }
  27469. return t;
  27470. };
  27471. var BABYLON;
  27472. (function (BABYLON) {
  27473. var MaterialDefines = /** @class */ (function () {
  27474. function MaterialDefines() {
  27475. this._isDirty = true;
  27476. this._areLightsDirty = true;
  27477. this._areAttributesDirty = true;
  27478. this._areTexturesDirty = true;
  27479. this._areFresnelDirty = true;
  27480. this._areMiscDirty = true;
  27481. this._areImageProcessingDirty = true;
  27482. this._normals = false;
  27483. this._uvs = false;
  27484. this._needNormals = false;
  27485. this._needUVs = false;
  27486. }
  27487. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27488. get: function () {
  27489. return this._isDirty;
  27490. },
  27491. enumerable: true,
  27492. configurable: true
  27493. });
  27494. MaterialDefines.prototype.markAsProcessed = function () {
  27495. this._isDirty = false;
  27496. this._areAttributesDirty = false;
  27497. this._areTexturesDirty = false;
  27498. this._areFresnelDirty = false;
  27499. this._areLightsDirty = false;
  27500. this._areMiscDirty = false;
  27501. this._areImageProcessingDirty = false;
  27502. };
  27503. MaterialDefines.prototype.markAsUnprocessed = function () {
  27504. this._isDirty = true;
  27505. };
  27506. MaterialDefines.prototype.markAllAsDirty = function () {
  27507. this._areTexturesDirty = true;
  27508. this._areAttributesDirty = true;
  27509. this._areLightsDirty = true;
  27510. this._areFresnelDirty = true;
  27511. this._areMiscDirty = true;
  27512. this._areImageProcessingDirty = true;
  27513. this._isDirty = true;
  27514. };
  27515. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27516. this._areImageProcessingDirty = true;
  27517. this._isDirty = true;
  27518. };
  27519. MaterialDefines.prototype.markAsLightDirty = function () {
  27520. this._areLightsDirty = true;
  27521. this._isDirty = true;
  27522. };
  27523. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27524. this._areAttributesDirty = true;
  27525. this._isDirty = true;
  27526. };
  27527. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27528. this._areTexturesDirty = true;
  27529. this._isDirty = true;
  27530. };
  27531. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27532. this._areFresnelDirty = true;
  27533. this._isDirty = true;
  27534. };
  27535. MaterialDefines.prototype.markAsMiscDirty = function () {
  27536. this._areMiscDirty = true;
  27537. this._isDirty = true;
  27538. };
  27539. MaterialDefines.prototype.rebuild = function () {
  27540. if (this._keys) {
  27541. delete this._keys;
  27542. }
  27543. this._keys = [];
  27544. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27545. var key = _a[_i];
  27546. if (key[0] === "_") {
  27547. continue;
  27548. }
  27549. this._keys.push(key);
  27550. }
  27551. };
  27552. MaterialDefines.prototype.isEqual = function (other) {
  27553. if (this._keys.length !== other._keys.length) {
  27554. return false;
  27555. }
  27556. for (var index = 0; index < this._keys.length; index++) {
  27557. var prop = this._keys[index];
  27558. if (this[prop] !== other[prop]) {
  27559. return false;
  27560. }
  27561. }
  27562. return true;
  27563. };
  27564. MaterialDefines.prototype.cloneTo = function (other) {
  27565. if (this._keys.length !== other._keys.length) {
  27566. other._keys = this._keys.slice(0);
  27567. }
  27568. for (var index = 0; index < this._keys.length; index++) {
  27569. var prop = this._keys[index];
  27570. other[prop] = this[prop];
  27571. }
  27572. };
  27573. MaterialDefines.prototype.reset = function () {
  27574. for (var index = 0; index < this._keys.length; index++) {
  27575. var prop = this._keys[index];
  27576. if (typeof (this[prop]) === "number") {
  27577. this[prop] = 0;
  27578. }
  27579. else {
  27580. this[prop] = false;
  27581. }
  27582. }
  27583. };
  27584. MaterialDefines.prototype.toString = function () {
  27585. var result = "";
  27586. for (var index = 0; index < this._keys.length; index++) {
  27587. var prop = this._keys[index];
  27588. var value = this[prop];
  27589. if (typeof (value) === "number") {
  27590. result += "#define " + prop + " " + this[prop] + "\n";
  27591. }
  27592. else if (value) {
  27593. result += "#define " + prop + "\n";
  27594. }
  27595. }
  27596. return result;
  27597. };
  27598. return MaterialDefines;
  27599. }());
  27600. BABYLON.MaterialDefines = MaterialDefines;
  27601. var Material = /** @class */ (function () {
  27602. function Material(name, scene, doNotAdd) {
  27603. this.checkReadyOnEveryCall = false;
  27604. this.checkReadyOnlyOnce = false;
  27605. this.state = "";
  27606. this.alpha = 1.0;
  27607. this._backFaceCulling = true;
  27608. this.doNotSerialize = false;
  27609. this.storeEffectOnSubMeshes = false;
  27610. /**
  27611. * An event triggered when the material is disposed.
  27612. * @type {BABYLON.Observable}
  27613. */
  27614. this.onDisposeObservable = new BABYLON.Observable();
  27615. /**
  27616. * An event triggered when the material is bound.
  27617. * @type {BABYLON.Observable}
  27618. */
  27619. this.onBindObservable = new BABYLON.Observable();
  27620. /**
  27621. * An event triggered when the material is unbound.
  27622. * @type {BABYLON.Observable}
  27623. */
  27624. this.onUnBindObservable = new BABYLON.Observable();
  27625. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27626. this._needDepthPrePass = false;
  27627. this.disableDepthWrite = false;
  27628. this.forceDepthWrite = false;
  27629. this.separateCullingPass = false;
  27630. this._fogEnabled = true;
  27631. this.pointSize = 1.0;
  27632. this.zOffset = 0;
  27633. this._wasPreviouslyReady = false;
  27634. this._fillMode = Material.TriangleFillMode;
  27635. this.name = name;
  27636. this.id = name || BABYLON.Tools.RandomId();
  27637. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27638. if (this._scene.useRightHandedSystem) {
  27639. this.sideOrientation = Material.ClockWiseSideOrientation;
  27640. }
  27641. else {
  27642. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27643. }
  27644. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27645. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27646. if (!doNotAdd) {
  27647. this._scene.materials.push(this);
  27648. }
  27649. }
  27650. Object.defineProperty(Material, "TriangleFillMode", {
  27651. get: function () {
  27652. return Material._TriangleFillMode;
  27653. },
  27654. enumerable: true,
  27655. configurable: true
  27656. });
  27657. Object.defineProperty(Material, "WireFrameFillMode", {
  27658. get: function () {
  27659. return Material._WireFrameFillMode;
  27660. },
  27661. enumerable: true,
  27662. configurable: true
  27663. });
  27664. Object.defineProperty(Material, "PointFillMode", {
  27665. get: function () {
  27666. return Material._PointFillMode;
  27667. },
  27668. enumerable: true,
  27669. configurable: true
  27670. });
  27671. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27672. get: function () {
  27673. return Material._ClockWiseSideOrientation;
  27674. },
  27675. enumerable: true,
  27676. configurable: true
  27677. });
  27678. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27679. get: function () {
  27680. return Material._CounterClockWiseSideOrientation;
  27681. },
  27682. enumerable: true,
  27683. configurable: true
  27684. });
  27685. Object.defineProperty(Material, "TextureDirtyFlag", {
  27686. get: function () {
  27687. return Material._TextureDirtyFlag;
  27688. },
  27689. enumerable: true,
  27690. configurable: true
  27691. });
  27692. Object.defineProperty(Material, "LightDirtyFlag", {
  27693. get: function () {
  27694. return Material._LightDirtyFlag;
  27695. },
  27696. enumerable: true,
  27697. configurable: true
  27698. });
  27699. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27700. get: function () {
  27701. return Material._FresnelDirtyFlag;
  27702. },
  27703. enumerable: true,
  27704. configurable: true
  27705. });
  27706. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27707. get: function () {
  27708. return Material._AttributesDirtyFlag;
  27709. },
  27710. enumerable: true,
  27711. configurable: true
  27712. });
  27713. Object.defineProperty(Material, "MiscDirtyFlag", {
  27714. get: function () {
  27715. return Material._MiscDirtyFlag;
  27716. },
  27717. enumerable: true,
  27718. configurable: true
  27719. });
  27720. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27721. get: function () {
  27722. return this._backFaceCulling;
  27723. },
  27724. set: function (value) {
  27725. if (this._backFaceCulling === value) {
  27726. return;
  27727. }
  27728. this._backFaceCulling = value;
  27729. this.markAsDirty(Material.TextureDirtyFlag);
  27730. },
  27731. enumerable: true,
  27732. configurable: true
  27733. });
  27734. Object.defineProperty(Material.prototype, "onDispose", {
  27735. set: function (callback) {
  27736. if (this._onDisposeObserver) {
  27737. this.onDisposeObservable.remove(this._onDisposeObserver);
  27738. }
  27739. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27740. },
  27741. enumerable: true,
  27742. configurable: true
  27743. });
  27744. Object.defineProperty(Material.prototype, "onBind", {
  27745. set: function (callback) {
  27746. if (this._onBindObserver) {
  27747. this.onBindObservable.remove(this._onBindObserver);
  27748. }
  27749. this._onBindObserver = this.onBindObservable.add(callback);
  27750. },
  27751. enumerable: true,
  27752. configurable: true
  27753. });
  27754. Object.defineProperty(Material.prototype, "alphaMode", {
  27755. get: function () {
  27756. return this._alphaMode;
  27757. },
  27758. set: function (value) {
  27759. if (this._alphaMode === value) {
  27760. return;
  27761. }
  27762. this._alphaMode = value;
  27763. this.markAsDirty(Material.TextureDirtyFlag);
  27764. },
  27765. enumerable: true,
  27766. configurable: true
  27767. });
  27768. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27769. get: function () {
  27770. return this._needDepthPrePass;
  27771. },
  27772. set: function (value) {
  27773. if (this._needDepthPrePass === value) {
  27774. return;
  27775. }
  27776. this._needDepthPrePass = value;
  27777. if (this._needDepthPrePass) {
  27778. this.checkReadyOnEveryCall = true;
  27779. }
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. Object.defineProperty(Material.prototype, "fogEnabled", {
  27785. get: function () {
  27786. return this._fogEnabled;
  27787. },
  27788. set: function (value) {
  27789. if (this._fogEnabled === value) {
  27790. return;
  27791. }
  27792. this._fogEnabled = value;
  27793. this.markAsDirty(Material.MiscDirtyFlag);
  27794. },
  27795. enumerable: true,
  27796. configurable: true
  27797. });
  27798. Object.defineProperty(Material.prototype, "wireframe", {
  27799. get: function () {
  27800. return this._fillMode === Material.WireFrameFillMode;
  27801. },
  27802. set: function (value) {
  27803. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27804. },
  27805. enumerable: true,
  27806. configurable: true
  27807. });
  27808. Object.defineProperty(Material.prototype, "pointsCloud", {
  27809. get: function () {
  27810. return this._fillMode === Material.PointFillMode;
  27811. },
  27812. set: function (value) {
  27813. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27814. },
  27815. enumerable: true,
  27816. configurable: true
  27817. });
  27818. Object.defineProperty(Material.prototype, "fillMode", {
  27819. get: function () {
  27820. return this._fillMode;
  27821. },
  27822. set: function (value) {
  27823. if (this._fillMode === value) {
  27824. return;
  27825. }
  27826. this._fillMode = value;
  27827. this.markAsDirty(Material.MiscDirtyFlag);
  27828. },
  27829. enumerable: true,
  27830. configurable: true
  27831. });
  27832. /**
  27833. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27834. * subclasses should override adding information pertainent to themselves
  27835. */
  27836. Material.prototype.toString = function (fullDetails) {
  27837. var ret = "Name: " + this.name;
  27838. if (fullDetails) {
  27839. }
  27840. return ret;
  27841. };
  27842. /**
  27843. * Child classes can use it to update shaders
  27844. */
  27845. Material.prototype.getClassName = function () {
  27846. return "Material";
  27847. };
  27848. Object.defineProperty(Material.prototype, "isFrozen", {
  27849. get: function () {
  27850. return this.checkReadyOnlyOnce;
  27851. },
  27852. enumerable: true,
  27853. configurable: true
  27854. });
  27855. Material.prototype.freeze = function () {
  27856. this.checkReadyOnlyOnce = true;
  27857. };
  27858. Material.prototype.unfreeze = function () {
  27859. this.checkReadyOnlyOnce = false;
  27860. };
  27861. Material.prototype.isReady = function (mesh, useInstances) {
  27862. return true;
  27863. };
  27864. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27865. return false;
  27866. };
  27867. Material.prototype.getEffect = function () {
  27868. return this._effect;
  27869. };
  27870. Material.prototype.getScene = function () {
  27871. return this._scene;
  27872. };
  27873. Material.prototype.needAlphaBlending = function () {
  27874. return (this.alpha < 1.0);
  27875. };
  27876. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27877. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27878. };
  27879. Material.prototype.needAlphaTesting = function () {
  27880. return false;
  27881. };
  27882. Material.prototype.getAlphaTestTexture = function () {
  27883. return null;
  27884. };
  27885. Material.prototype.markDirty = function () {
  27886. this._wasPreviouslyReady = false;
  27887. };
  27888. Material.prototype._preBind = function (effect, overrideOrientation) {
  27889. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27890. var engine = this._scene.getEngine();
  27891. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27892. var reverse = orientation === Material.ClockWiseSideOrientation;
  27893. engine.enableEffect(effect ? effect : this._effect);
  27894. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27895. return reverse;
  27896. };
  27897. Material.prototype.bind = function (world, mesh) {
  27898. };
  27899. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27900. };
  27901. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27902. };
  27903. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27904. sceneUbo.bindToEffect(effect, "Scene");
  27905. };
  27906. Material.prototype.bindView = function (effect) {
  27907. if (!this._useUBO) {
  27908. effect.setMatrix("view", this.getScene().getViewMatrix());
  27909. }
  27910. else {
  27911. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27912. }
  27913. };
  27914. Material.prototype.bindViewProjection = function (effect) {
  27915. if (!this._useUBO) {
  27916. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27917. }
  27918. else {
  27919. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27920. }
  27921. };
  27922. Material.prototype._afterBind = function (mesh) {
  27923. this._scene._cachedMaterial = this;
  27924. if (mesh) {
  27925. this._scene._cachedVisibility = mesh.visibility;
  27926. }
  27927. else {
  27928. this._scene._cachedVisibility = 1;
  27929. }
  27930. if (mesh) {
  27931. this.onBindObservable.notifyObservers(mesh);
  27932. }
  27933. if (this.disableDepthWrite) {
  27934. var engine = this._scene.getEngine();
  27935. this._cachedDepthWriteState = engine.getDepthWrite();
  27936. engine.setDepthWrite(false);
  27937. }
  27938. };
  27939. Material.prototype.unbind = function () {
  27940. this.onUnBindObservable.notifyObservers(this);
  27941. if (this.disableDepthWrite) {
  27942. var engine = this._scene.getEngine();
  27943. engine.setDepthWrite(this._cachedDepthWriteState);
  27944. }
  27945. };
  27946. Material.prototype.getActiveTextures = function () {
  27947. return [];
  27948. };
  27949. Material.prototype.hasTexture = function (texture) {
  27950. return false;
  27951. };
  27952. Material.prototype.clone = function (name) {
  27953. return null;
  27954. };
  27955. Material.prototype.getBindedMeshes = function () {
  27956. var result = new Array();
  27957. for (var index = 0; index < this._scene.meshes.length; index++) {
  27958. var mesh = this._scene.meshes[index];
  27959. if (mesh.material === this) {
  27960. result.push(mesh);
  27961. }
  27962. }
  27963. return result;
  27964. };
  27965. /**
  27966. * Force shader compilation including textures ready check
  27967. */
  27968. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27969. var _this = this;
  27970. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27971. var subMesh = new BABYLON.BaseSubMesh();
  27972. var scene = this.getScene();
  27973. var engine = scene.getEngine();
  27974. var checkReady = function () {
  27975. if (!_this._scene || !_this._scene.getEngine()) {
  27976. return;
  27977. }
  27978. if (subMesh._materialDefines) {
  27979. subMesh._materialDefines._renderId = -1;
  27980. }
  27981. var alphaTestState = engine.getAlphaTesting();
  27982. var clipPlaneState = scene.clipPlane;
  27983. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27984. if (localOptions.clipPlane) {
  27985. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27986. }
  27987. if (_this.storeEffectOnSubMeshes) {
  27988. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27989. if (onCompiled) {
  27990. onCompiled(_this);
  27991. }
  27992. }
  27993. else {
  27994. setTimeout(checkReady, 16);
  27995. }
  27996. }
  27997. else {
  27998. if (_this.isReady(mesh)) {
  27999. if (onCompiled) {
  28000. onCompiled(_this);
  28001. }
  28002. }
  28003. else {
  28004. setTimeout(checkReady, 16);
  28005. }
  28006. }
  28007. engine.setAlphaTesting(alphaTestState);
  28008. if (options && options.clipPlane) {
  28009. scene.clipPlane = clipPlaneState;
  28010. }
  28011. };
  28012. checkReady();
  28013. };
  28014. Material.prototype.markAsDirty = function (flag) {
  28015. if (flag & Material.TextureDirtyFlag) {
  28016. this._markAllSubMeshesAsTexturesDirty();
  28017. }
  28018. if (flag & Material.LightDirtyFlag) {
  28019. this._markAllSubMeshesAsLightsDirty();
  28020. }
  28021. if (flag & Material.FresnelDirtyFlag) {
  28022. this._markAllSubMeshesAsFresnelDirty();
  28023. }
  28024. if (flag & Material.AttributesDirtyFlag) {
  28025. this._markAllSubMeshesAsAttributesDirty();
  28026. }
  28027. if (flag & Material.MiscDirtyFlag) {
  28028. this._markAllSubMeshesAsMiscDirty();
  28029. }
  28030. this.getScene().resetCachedMaterial();
  28031. };
  28032. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28033. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28034. var mesh = _a[_i];
  28035. if (!mesh.subMeshes) {
  28036. continue;
  28037. }
  28038. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28039. var subMesh = _c[_b];
  28040. if (subMesh.getMaterial() !== this) {
  28041. continue;
  28042. }
  28043. if (!subMesh._materialDefines) {
  28044. continue;
  28045. }
  28046. func(subMesh._materialDefines);
  28047. }
  28048. }
  28049. };
  28050. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28051. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28052. };
  28053. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28054. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28055. };
  28056. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28057. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28058. };
  28059. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28060. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28061. };
  28062. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28063. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28064. };
  28065. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28066. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28067. };
  28068. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28069. // Animations
  28070. this.getScene().stopAnimation(this);
  28071. // Remove from scene
  28072. var index = this._scene.materials.indexOf(this);
  28073. if (index >= 0) {
  28074. this._scene.materials.splice(index, 1);
  28075. }
  28076. // Remove from meshes
  28077. for (index = 0; index < this._scene.meshes.length; index++) {
  28078. var mesh = this._scene.meshes[index];
  28079. if (mesh.material === this) {
  28080. mesh.material = null;
  28081. if (mesh.geometry) {
  28082. var geometry = (mesh.geometry);
  28083. if (this.storeEffectOnSubMeshes) {
  28084. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28085. var subMesh = _a[_i];
  28086. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28087. if (forceDisposeEffect && subMesh._materialEffect) {
  28088. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28089. }
  28090. }
  28091. }
  28092. else {
  28093. geometry._releaseVertexArrayObject(this._effect);
  28094. }
  28095. }
  28096. }
  28097. }
  28098. this._uniformBuffer.dispose();
  28099. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28100. if (forceDisposeEffect && this._effect) {
  28101. if (!this.storeEffectOnSubMeshes) {
  28102. this._scene.getEngine()._releaseEffect(this._effect);
  28103. }
  28104. this._effect = null;
  28105. }
  28106. // Callback
  28107. this.onDisposeObservable.notifyObservers(this);
  28108. this.onDisposeObservable.clear();
  28109. this.onBindObservable.clear();
  28110. this.onUnBindObservable.clear();
  28111. };
  28112. Material.prototype.serialize = function () {
  28113. return BABYLON.SerializationHelper.Serialize(this);
  28114. };
  28115. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28116. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28117. multiMaterial.id = parsedMultiMaterial.id;
  28118. if (BABYLON.Tags) {
  28119. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28120. }
  28121. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28122. var subMatId = parsedMultiMaterial.materials[matIndex];
  28123. if (subMatId) {
  28124. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28125. }
  28126. else {
  28127. multiMaterial.subMaterials.push(null);
  28128. }
  28129. }
  28130. return multiMaterial;
  28131. };
  28132. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28133. if (!parsedMaterial.customType) {
  28134. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28135. }
  28136. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28137. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28138. if (!BABYLON.LegacyPBRMaterial) {
  28139. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28140. return;
  28141. }
  28142. }
  28143. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28144. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28145. ;
  28146. };
  28147. Material._TriangleFillMode = 0;
  28148. Material._WireFrameFillMode = 1;
  28149. Material._PointFillMode = 2;
  28150. Material._ClockWiseSideOrientation = 0;
  28151. Material._CounterClockWiseSideOrientation = 1;
  28152. Material._TextureDirtyFlag = 1;
  28153. Material._LightDirtyFlag = 2;
  28154. Material._FresnelDirtyFlag = 4;
  28155. Material._AttributesDirtyFlag = 8;
  28156. Material._MiscDirtyFlag = 16;
  28157. __decorate([
  28158. BABYLON.serialize()
  28159. ], Material.prototype, "id", void 0);
  28160. __decorate([
  28161. BABYLON.serialize()
  28162. ], Material.prototype, "name", void 0);
  28163. __decorate([
  28164. BABYLON.serialize()
  28165. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28166. __decorate([
  28167. BABYLON.serialize()
  28168. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28169. __decorate([
  28170. BABYLON.serialize()
  28171. ], Material.prototype, "state", void 0);
  28172. __decorate([
  28173. BABYLON.serialize()
  28174. ], Material.prototype, "alpha", void 0);
  28175. __decorate([
  28176. BABYLON.serialize("backFaceCulling")
  28177. ], Material.prototype, "_backFaceCulling", void 0);
  28178. __decorate([
  28179. BABYLON.serialize()
  28180. ], Material.prototype, "sideOrientation", void 0);
  28181. __decorate([
  28182. BABYLON.serialize("alphaMode")
  28183. ], Material.prototype, "_alphaMode", void 0);
  28184. __decorate([
  28185. BABYLON.serialize()
  28186. ], Material.prototype, "_needDepthPrePass", void 0);
  28187. __decorate([
  28188. BABYLON.serialize()
  28189. ], Material.prototype, "disableDepthWrite", void 0);
  28190. __decorate([
  28191. BABYLON.serialize()
  28192. ], Material.prototype, "forceDepthWrite", void 0);
  28193. __decorate([
  28194. BABYLON.serialize()
  28195. ], Material.prototype, "separateCullingPass", void 0);
  28196. __decorate([
  28197. BABYLON.serialize("fogEnabled")
  28198. ], Material.prototype, "_fogEnabled", void 0);
  28199. __decorate([
  28200. BABYLON.serialize()
  28201. ], Material.prototype, "pointSize", void 0);
  28202. __decorate([
  28203. BABYLON.serialize()
  28204. ], Material.prototype, "zOffset", void 0);
  28205. __decorate([
  28206. BABYLON.serialize()
  28207. ], Material.prototype, "wireframe", null);
  28208. __decorate([
  28209. BABYLON.serialize()
  28210. ], Material.prototype, "pointsCloud", null);
  28211. __decorate([
  28212. BABYLON.serialize()
  28213. ], Material.prototype, "fillMode", null);
  28214. return Material;
  28215. }());
  28216. BABYLON.Material = Material;
  28217. })(BABYLON || (BABYLON = {}));
  28218. //# sourceMappingURL=babylon.material.js.map
  28219. var BABYLON;
  28220. (function (BABYLON) {
  28221. var UniformBuffer = /** @class */ (function () {
  28222. /**
  28223. * Uniform buffer objects.
  28224. *
  28225. * Handles blocks of uniform on the GPU.
  28226. *
  28227. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28228. *
  28229. * For more information, please refer to :
  28230. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28231. */
  28232. function UniformBuffer(engine, data, dynamic) {
  28233. this._engine = engine;
  28234. this._noUBO = !engine.supportsUniformBuffers;
  28235. this._dynamic = dynamic;
  28236. this._data = data || [];
  28237. this._uniformLocations = {};
  28238. this._uniformSizes = {};
  28239. this._uniformLocationPointer = 0;
  28240. this._needSync = false;
  28241. if (this._noUBO) {
  28242. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28243. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28244. this.updateFloat = this._updateFloatForEffect;
  28245. this.updateFloat2 = this._updateFloat2ForEffect;
  28246. this.updateFloat3 = this._updateFloat3ForEffect;
  28247. this.updateFloat4 = this._updateFloat4ForEffect;
  28248. this.updateMatrix = this._updateMatrixForEffect;
  28249. this.updateVector3 = this._updateVector3ForEffect;
  28250. this.updateVector4 = this._updateVector4ForEffect;
  28251. this.updateColor3 = this._updateColor3ForEffect;
  28252. this.updateColor4 = this._updateColor4ForEffect;
  28253. }
  28254. else {
  28255. this._engine._uniformBuffers.push(this);
  28256. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28257. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28258. this.updateFloat = this._updateFloatForUniform;
  28259. this.updateFloat2 = this._updateFloat2ForUniform;
  28260. this.updateFloat3 = this._updateFloat3ForUniform;
  28261. this.updateFloat4 = this._updateFloat4ForUniform;
  28262. this.updateMatrix = this._updateMatrixForUniform;
  28263. this.updateVector3 = this._updateVector3ForUniform;
  28264. this.updateVector4 = this._updateVector4ForUniform;
  28265. this.updateColor3 = this._updateColor3ForUniform;
  28266. this.updateColor4 = this._updateColor4ForUniform;
  28267. }
  28268. }
  28269. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28270. // Properties
  28271. /**
  28272. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28273. * or just falling back on setUniformXXX calls.
  28274. */
  28275. get: function () {
  28276. return !this._noUBO;
  28277. },
  28278. enumerable: true,
  28279. configurable: true
  28280. });
  28281. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28282. /**
  28283. * Indicates if the WebGL underlying uniform buffer is in sync
  28284. * with the javascript cache data.
  28285. */
  28286. get: function () {
  28287. return !this._needSync;
  28288. },
  28289. enumerable: true,
  28290. configurable: true
  28291. });
  28292. /**
  28293. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28294. * Also, a dynamic UniformBuffer will disable cache verification and always
  28295. * update the underlying WebGL uniform buffer to the GPU.
  28296. */
  28297. UniformBuffer.prototype.isDynamic = function () {
  28298. return this._dynamic !== undefined;
  28299. };
  28300. /**
  28301. * The data cache on JS side.
  28302. */
  28303. UniformBuffer.prototype.getData = function () {
  28304. return this._bufferData;
  28305. };
  28306. /**
  28307. * The underlying WebGL Uniform buffer.
  28308. */
  28309. UniformBuffer.prototype.getBuffer = function () {
  28310. return this._buffer;
  28311. };
  28312. /**
  28313. * std140 layout specifies how to align data within an UBO structure.
  28314. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28315. * for specs.
  28316. */
  28317. UniformBuffer.prototype._fillAlignment = function (size) {
  28318. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28319. // and 4x4 matrices
  28320. // TODO : change if other types are used
  28321. var alignment;
  28322. if (size <= 2) {
  28323. alignment = size;
  28324. }
  28325. else {
  28326. alignment = 4;
  28327. }
  28328. if ((this._uniformLocationPointer % alignment) !== 0) {
  28329. var oldPointer = this._uniformLocationPointer;
  28330. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28331. var diff = this._uniformLocationPointer - oldPointer;
  28332. for (var i = 0; i < diff; i++) {
  28333. this._data.push(0);
  28334. }
  28335. }
  28336. };
  28337. /**
  28338. * Adds an uniform in the buffer.
  28339. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28340. * for the layout to be correct !
  28341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28342. * @param {number|number[]} size Data size, or data directly.
  28343. */
  28344. UniformBuffer.prototype.addUniform = function (name, size) {
  28345. if (this._noUBO) {
  28346. return;
  28347. }
  28348. if (this._uniformLocations[name] !== undefined) {
  28349. // Already existing uniform
  28350. return;
  28351. }
  28352. // This function must be called in the order of the shader layout !
  28353. // size can be the size of the uniform, or data directly
  28354. var data;
  28355. if (size instanceof Array) {
  28356. data = size;
  28357. size = data.length;
  28358. }
  28359. else {
  28360. size = size;
  28361. data = [];
  28362. // Fill with zeros
  28363. for (var i = 0; i < size; i++) {
  28364. data.push(0);
  28365. }
  28366. }
  28367. this._fillAlignment(size);
  28368. this._uniformSizes[name] = size;
  28369. this._uniformLocations[name] = this._uniformLocationPointer;
  28370. this._uniformLocationPointer += size;
  28371. for (var i = 0; i < size; i++) {
  28372. this._data.push(data[i]);
  28373. }
  28374. this._needSync = true;
  28375. };
  28376. /**
  28377. * Wrapper for addUniform.
  28378. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28379. * @param {Matrix} mat A 4x4 matrix.
  28380. */
  28381. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28382. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28383. };
  28384. /**
  28385. * Wrapper for addUniform.
  28386. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28387. * @param {number} x
  28388. * @param {number} y
  28389. */
  28390. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28391. var temp = [x, y];
  28392. this.addUniform(name, temp);
  28393. };
  28394. /**
  28395. * Wrapper for addUniform.
  28396. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28397. * @param {number} x
  28398. * @param {number} y
  28399. * @param {number} z
  28400. */
  28401. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28402. var temp = [x, y, z];
  28403. this.addUniform(name, temp);
  28404. };
  28405. /**
  28406. * Wrapper for addUniform.
  28407. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28408. * @param {Color3} color
  28409. */
  28410. UniformBuffer.prototype.addColor3 = function (name, color) {
  28411. var temp = new Array();
  28412. color.toArray(temp);
  28413. this.addUniform(name, temp);
  28414. };
  28415. /**
  28416. * Wrapper for addUniform.
  28417. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28418. * @param {Color3} color
  28419. * @param {number} alpha
  28420. */
  28421. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28422. var temp = new Array();
  28423. color.toArray(temp);
  28424. temp.push(alpha);
  28425. this.addUniform(name, temp);
  28426. };
  28427. /**
  28428. * Wrapper for addUniform.
  28429. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28430. * @param {Vector3} vector
  28431. */
  28432. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28433. var temp = new Array();
  28434. vector.toArray(temp);
  28435. this.addUniform(name, temp);
  28436. };
  28437. /**
  28438. * Wrapper for addUniform.
  28439. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28440. */
  28441. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28442. this.addUniform(name, 12);
  28443. };
  28444. /**
  28445. * Wrapper for addUniform.
  28446. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28447. */
  28448. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28449. this.addUniform(name, 8);
  28450. };
  28451. /**
  28452. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28453. */
  28454. UniformBuffer.prototype.create = function () {
  28455. if (this._noUBO) {
  28456. return;
  28457. }
  28458. if (this._buffer) {
  28459. return; // nothing to do
  28460. }
  28461. // See spec, alignment must be filled as a vec4
  28462. this._fillAlignment(4);
  28463. this._bufferData = new Float32Array(this._data);
  28464. this._rebuild();
  28465. this._needSync = true;
  28466. };
  28467. UniformBuffer.prototype._rebuild = function () {
  28468. if (this._noUBO) {
  28469. return;
  28470. }
  28471. if (this._dynamic) {
  28472. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28473. }
  28474. else {
  28475. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28476. }
  28477. };
  28478. /**
  28479. * Updates the WebGL Uniform Buffer on the GPU.
  28480. * If the `dynamic` flag is set to true, no cache comparison is done.
  28481. * Otherwise, the buffer will be updated only if the cache differs.
  28482. */
  28483. UniformBuffer.prototype.update = function () {
  28484. if (!this._buffer) {
  28485. this.create();
  28486. return;
  28487. }
  28488. if (!this._dynamic && !this._needSync) {
  28489. return;
  28490. }
  28491. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28492. this._needSync = false;
  28493. };
  28494. /**
  28495. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28496. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28497. * @param {number[]|Float32Array} data Flattened data
  28498. * @param {number} size Size of the data.
  28499. */
  28500. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28501. var location = this._uniformLocations[uniformName];
  28502. if (location === undefined) {
  28503. if (this._buffer) {
  28504. // Cannot add an uniform if the buffer is already created
  28505. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28506. return;
  28507. }
  28508. this.addUniform(uniformName, size);
  28509. location = this._uniformLocations[uniformName];
  28510. }
  28511. if (!this._buffer) {
  28512. this.create();
  28513. }
  28514. if (!this._dynamic) {
  28515. // Cache for static uniform buffers
  28516. var changed = false;
  28517. for (var i = 0; i < size; i++) {
  28518. if (this._bufferData[location + i] !== data[i]) {
  28519. changed = true;
  28520. this._bufferData[location + i] = data[i];
  28521. }
  28522. }
  28523. this._needSync = this._needSync || changed;
  28524. }
  28525. else {
  28526. // No cache for dynamic
  28527. for (var i = 0; i < size; i++) {
  28528. this._bufferData[location + i] = data[i];
  28529. }
  28530. }
  28531. };
  28532. // Update methods
  28533. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28534. // To match std140, matrix must be realigned
  28535. for (var i = 0; i < 3; i++) {
  28536. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28537. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28538. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28539. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28540. }
  28541. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28542. };
  28543. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28544. this._currentEffect.setMatrix3x3(name, matrix);
  28545. };
  28546. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28547. this._currentEffect.setMatrix2x2(name, matrix);
  28548. };
  28549. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28550. // To match std140, matrix must be realigned
  28551. for (var i = 0; i < 2; i++) {
  28552. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28553. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28554. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28555. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28556. }
  28557. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28558. };
  28559. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28560. this._currentEffect.setFloat(name, x);
  28561. };
  28562. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28563. UniformBuffer._tempBuffer[0] = x;
  28564. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28565. };
  28566. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28567. if (suffix === void 0) { suffix = ""; }
  28568. this._currentEffect.setFloat2(name + suffix, x, y);
  28569. };
  28570. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28571. if (suffix === void 0) { suffix = ""; }
  28572. UniformBuffer._tempBuffer[0] = x;
  28573. UniformBuffer._tempBuffer[1] = y;
  28574. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28575. };
  28576. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28577. if (suffix === void 0) { suffix = ""; }
  28578. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28579. };
  28580. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28581. if (suffix === void 0) { suffix = ""; }
  28582. UniformBuffer._tempBuffer[0] = x;
  28583. UniformBuffer._tempBuffer[1] = y;
  28584. UniformBuffer._tempBuffer[2] = z;
  28585. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28586. };
  28587. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28588. if (suffix === void 0) { suffix = ""; }
  28589. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28590. };
  28591. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28592. if (suffix === void 0) { suffix = ""; }
  28593. UniformBuffer._tempBuffer[0] = x;
  28594. UniformBuffer._tempBuffer[1] = y;
  28595. UniformBuffer._tempBuffer[2] = z;
  28596. UniformBuffer._tempBuffer[3] = w;
  28597. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28598. };
  28599. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28600. this._currentEffect.setMatrix(name, mat);
  28601. };
  28602. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28603. this.updateUniform(name, mat.toArray(), 16);
  28604. };
  28605. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28606. this._currentEffect.setVector3(name, vector);
  28607. };
  28608. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28609. vector.toArray(UniformBuffer._tempBuffer);
  28610. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28611. };
  28612. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28613. this._currentEffect.setVector4(name, vector);
  28614. };
  28615. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28616. vector.toArray(UniformBuffer._tempBuffer);
  28617. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28618. };
  28619. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28620. if (suffix === void 0) { suffix = ""; }
  28621. this._currentEffect.setColor3(name + suffix, color);
  28622. };
  28623. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28624. if (suffix === void 0) { suffix = ""; }
  28625. color.toArray(UniformBuffer._tempBuffer);
  28626. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28627. };
  28628. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28629. if (suffix === void 0) { suffix = ""; }
  28630. this._currentEffect.setColor4(name + suffix, color, alpha);
  28631. };
  28632. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28633. if (suffix === void 0) { suffix = ""; }
  28634. color.toArray(UniformBuffer._tempBuffer);
  28635. UniformBuffer._tempBuffer[3] = alpha;
  28636. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28637. };
  28638. /**
  28639. * Sets a sampler uniform on the effect.
  28640. * @param {string} name Name of the sampler.
  28641. * @param {Texture} texture
  28642. */
  28643. UniformBuffer.prototype.setTexture = function (name, texture) {
  28644. this._currentEffect.setTexture(name, texture);
  28645. };
  28646. /**
  28647. * Directly updates the value of the uniform in the cache AND on the GPU.
  28648. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28649. * @param {number[]|Float32Array} data Flattened data
  28650. */
  28651. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28652. this.updateUniform(uniformName, data, data.length);
  28653. this.update();
  28654. };
  28655. /**
  28656. * Binds this uniform buffer to an effect.
  28657. * @param {Effect} effect
  28658. * @param {string} name Name of the uniform block in the shader.
  28659. */
  28660. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28661. this._currentEffect = effect;
  28662. if (this._noUBO || !this._buffer) {
  28663. return;
  28664. }
  28665. effect.bindUniformBuffer(this._buffer, name);
  28666. };
  28667. /**
  28668. * Disposes the uniform buffer.
  28669. */
  28670. UniformBuffer.prototype.dispose = function () {
  28671. if (this._noUBO) {
  28672. return;
  28673. }
  28674. var index = this._engine._uniformBuffers.indexOf(this);
  28675. if (index !== -1) {
  28676. this._engine._uniformBuffers.splice(index, 1);
  28677. }
  28678. if (!this._buffer) {
  28679. return;
  28680. }
  28681. if (this._engine._releaseBuffer(this._buffer)) {
  28682. this._buffer = null;
  28683. }
  28684. };
  28685. // Pool for avoiding memory leaks
  28686. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28687. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28688. return UniformBuffer;
  28689. }());
  28690. BABYLON.UniformBuffer = UniformBuffer;
  28691. })(BABYLON || (BABYLON = {}));
  28692. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28693. var BABYLON;
  28694. (function (BABYLON) {
  28695. var PushMaterial = /** @class */ (function (_super) {
  28696. __extends(PushMaterial, _super);
  28697. function PushMaterial(name, scene) {
  28698. var _this = _super.call(this, name, scene) || this;
  28699. _this.storeEffectOnSubMeshes = true;
  28700. return _this;
  28701. }
  28702. PushMaterial.prototype.getEffect = function () {
  28703. return this._activeEffect;
  28704. };
  28705. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28706. if (!mesh) {
  28707. return false;
  28708. }
  28709. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28710. return true;
  28711. }
  28712. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28713. };
  28714. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28715. this._activeEffect.setMatrix("world", world);
  28716. };
  28717. PushMaterial.prototype.bind = function (world, mesh) {
  28718. if (!mesh) {
  28719. return;
  28720. }
  28721. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28722. };
  28723. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28724. if (effect === void 0) { effect = null; }
  28725. _super.prototype._afterBind.call(this, mesh);
  28726. this.getScene()._cachedEffect = effect;
  28727. };
  28728. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28729. if (visibility === void 0) { visibility = 1; }
  28730. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28731. };
  28732. return PushMaterial;
  28733. }(BABYLON.Material));
  28734. BABYLON.PushMaterial = PushMaterial;
  28735. })(BABYLON || (BABYLON = {}));
  28736. //# sourceMappingURL=babylon.pushMaterial.js.map
  28737. var BABYLON;
  28738. (function (BABYLON) {
  28739. var VertexData = /** @class */ (function () {
  28740. function VertexData() {
  28741. }
  28742. VertexData.prototype.set = function (data, kind) {
  28743. switch (kind) {
  28744. case BABYLON.VertexBuffer.PositionKind:
  28745. this.positions = data;
  28746. break;
  28747. case BABYLON.VertexBuffer.NormalKind:
  28748. this.normals = data;
  28749. break;
  28750. case BABYLON.VertexBuffer.TangentKind:
  28751. this.tangents = data;
  28752. break;
  28753. case BABYLON.VertexBuffer.UVKind:
  28754. this.uvs = data;
  28755. break;
  28756. case BABYLON.VertexBuffer.UV2Kind:
  28757. this.uvs2 = data;
  28758. break;
  28759. case BABYLON.VertexBuffer.UV3Kind:
  28760. this.uvs3 = data;
  28761. break;
  28762. case BABYLON.VertexBuffer.UV4Kind:
  28763. this.uvs4 = data;
  28764. break;
  28765. case BABYLON.VertexBuffer.UV5Kind:
  28766. this.uvs5 = data;
  28767. break;
  28768. case BABYLON.VertexBuffer.UV6Kind:
  28769. this.uvs6 = data;
  28770. break;
  28771. case BABYLON.VertexBuffer.ColorKind:
  28772. this.colors = data;
  28773. break;
  28774. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28775. this.matricesIndices = data;
  28776. break;
  28777. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28778. this.matricesWeights = data;
  28779. break;
  28780. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28781. this.matricesIndicesExtra = data;
  28782. break;
  28783. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28784. this.matricesWeightsExtra = data;
  28785. break;
  28786. }
  28787. };
  28788. /**
  28789. * Associates the vertexData to the passed Mesh.
  28790. * Sets it as updatable or not (default `false`).
  28791. * Returns the VertexData.
  28792. */
  28793. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28794. this._applyTo(mesh, updatable);
  28795. return this;
  28796. };
  28797. /**
  28798. * Associates the vertexData to the passed Geometry.
  28799. * Sets it as updatable or not (default `false`).
  28800. * Returns the VertexData.
  28801. */
  28802. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28803. this._applyTo(geometry, updatable);
  28804. return this;
  28805. };
  28806. /**
  28807. * Updates the associated mesh.
  28808. * Returns the VertexData.
  28809. */
  28810. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28811. this._update(mesh);
  28812. return this;
  28813. };
  28814. /**
  28815. * Updates the associated geometry.
  28816. * Returns the VertexData.
  28817. */
  28818. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28819. this._update(geometry);
  28820. return this;
  28821. };
  28822. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28823. if (updatable === void 0) { updatable = false; }
  28824. if (this.positions) {
  28825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28826. }
  28827. if (this.normals) {
  28828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28829. }
  28830. if (this.tangents) {
  28831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28832. }
  28833. if (this.uvs) {
  28834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28835. }
  28836. if (this.uvs2) {
  28837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28838. }
  28839. if (this.uvs3) {
  28840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28841. }
  28842. if (this.uvs4) {
  28843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28844. }
  28845. if (this.uvs5) {
  28846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28847. }
  28848. if (this.uvs6) {
  28849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28850. }
  28851. if (this.colors) {
  28852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28853. }
  28854. if (this.matricesIndices) {
  28855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28856. }
  28857. if (this.matricesWeights) {
  28858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28859. }
  28860. if (this.matricesIndicesExtra) {
  28861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28862. }
  28863. if (this.matricesWeightsExtra) {
  28864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28865. }
  28866. if (this.indices) {
  28867. meshOrGeometry.setIndices(this.indices, null, updatable);
  28868. }
  28869. return this;
  28870. };
  28871. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28872. if (this.positions) {
  28873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28874. }
  28875. if (this.normals) {
  28876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28877. }
  28878. if (this.tangents) {
  28879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28880. }
  28881. if (this.uvs) {
  28882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28883. }
  28884. if (this.uvs2) {
  28885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28886. }
  28887. if (this.uvs3) {
  28888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28889. }
  28890. if (this.uvs4) {
  28891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28892. }
  28893. if (this.uvs5) {
  28894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28895. }
  28896. if (this.uvs6) {
  28897. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28898. }
  28899. if (this.colors) {
  28900. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28901. }
  28902. if (this.matricesIndices) {
  28903. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28904. }
  28905. if (this.matricesWeights) {
  28906. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28907. }
  28908. if (this.matricesIndicesExtra) {
  28909. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28910. }
  28911. if (this.matricesWeightsExtra) {
  28912. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28913. }
  28914. if (this.indices) {
  28915. meshOrGeometry.setIndices(this.indices, null);
  28916. }
  28917. return this;
  28918. };
  28919. /**
  28920. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28921. * Returns the VertexData.
  28922. */
  28923. VertexData.prototype.transform = function (matrix) {
  28924. var transformed = BABYLON.Vector3.Zero();
  28925. var index;
  28926. if (this.positions) {
  28927. var position = BABYLON.Vector3.Zero();
  28928. for (index = 0; index < this.positions.length; index += 3) {
  28929. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28930. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28931. this.positions[index] = transformed.x;
  28932. this.positions[index + 1] = transformed.y;
  28933. this.positions[index + 2] = transformed.z;
  28934. }
  28935. }
  28936. if (this.normals) {
  28937. var normal = BABYLON.Vector3.Zero();
  28938. for (index = 0; index < this.normals.length; index += 3) {
  28939. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28940. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28941. this.normals[index] = transformed.x;
  28942. this.normals[index + 1] = transformed.y;
  28943. this.normals[index + 2] = transformed.z;
  28944. }
  28945. }
  28946. if (this.tangents) {
  28947. var tangent = BABYLON.Vector4.Zero();
  28948. var tangentTransformed = BABYLON.Vector4.Zero();
  28949. for (index = 0; index < this.tangents.length; index += 4) {
  28950. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28951. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28952. this.tangents[index] = tangentTransformed.x;
  28953. this.tangents[index + 1] = tangentTransformed.y;
  28954. this.tangents[index + 2] = tangentTransformed.z;
  28955. this.tangents[index + 3] = tangentTransformed.w;
  28956. }
  28957. }
  28958. return this;
  28959. };
  28960. /**
  28961. * Merges the passed VertexData into the current one.
  28962. * Returns the modified VertexData.
  28963. */
  28964. VertexData.prototype.merge = function (other, options) {
  28965. options = options || {};
  28966. if (other.indices) {
  28967. if (!this.indices) {
  28968. this.indices = [];
  28969. }
  28970. var offset = this.positions ? this.positions.length / 3 : 0;
  28971. for (var index = 0; index < other.indices.length; index++) {
  28972. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28973. this.indices.push(other.indices[index] + offset);
  28974. }
  28975. }
  28976. this.positions = this._mergeElement(this.positions, other.positions);
  28977. if (!this.positions) {
  28978. return this;
  28979. }
  28980. var count = this.positions.length / 3;
  28981. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28982. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28983. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28984. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28985. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28986. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28987. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28988. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28989. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28990. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28991. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28992. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28993. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28994. return this;
  28995. };
  28996. VertexData.prototype._mergeElement = function (source, other, length) {
  28997. if (length === void 0) { length = 0; }
  28998. if (!other && !source) {
  28999. return null;
  29000. }
  29001. if (!other) {
  29002. return this._mergeElement(source, new Float32Array(source.length), length);
  29003. }
  29004. if (!source) {
  29005. if (length === 0 || length === other.length) {
  29006. return other;
  29007. }
  29008. return this._mergeElement(new Float32Array(length - other.length), other, length);
  29009. }
  29010. var len = other.length + source.length;
  29011. var isSrcTypedArray = source instanceof Float32Array;
  29012. var isOthTypedArray = other instanceof Float32Array;
  29013. // use non-loop method when the source is Float32Array
  29014. if (isSrcTypedArray) {
  29015. var ret32 = new Float32Array(len);
  29016. ret32.set(source);
  29017. ret32.set(other, source.length);
  29018. return ret32;
  29019. // source is number[], when other is also use concat
  29020. }
  29021. else if (!isOthTypedArray) {
  29022. return source.concat(other);
  29023. // source is a number[], but other is a Float32Array, loop required
  29024. }
  29025. else {
  29026. var ret = source.slice(0); // copy source to a separate array
  29027. for (var i = 0, len = other.length; i < len; i++) {
  29028. ret.push(other[i]);
  29029. }
  29030. return ret;
  29031. }
  29032. };
  29033. /**
  29034. * Serializes the VertexData.
  29035. * Returns a serialized object.
  29036. */
  29037. VertexData.prototype.serialize = function () {
  29038. var serializationObject = this.serialize();
  29039. if (this.positions) {
  29040. serializationObject.positions = this.positions;
  29041. }
  29042. if (this.normals) {
  29043. serializationObject.normals = this.normals;
  29044. }
  29045. if (this.tangents) {
  29046. serializationObject.tangents = this.tangents;
  29047. }
  29048. if (this.uvs) {
  29049. serializationObject.uvs = this.uvs;
  29050. }
  29051. if (this.uvs2) {
  29052. serializationObject.uvs2 = this.uvs2;
  29053. }
  29054. if (this.uvs3) {
  29055. serializationObject.uvs3 = this.uvs3;
  29056. }
  29057. if (this.uvs4) {
  29058. serializationObject.uvs4 = this.uvs4;
  29059. }
  29060. if (this.uvs5) {
  29061. serializationObject.uvs5 = this.uvs5;
  29062. }
  29063. if (this.uvs6) {
  29064. serializationObject.uvs6 = this.uvs6;
  29065. }
  29066. if (this.colors) {
  29067. serializationObject.colors = this.colors;
  29068. }
  29069. if (this.matricesIndices) {
  29070. serializationObject.matricesIndices = this.matricesIndices;
  29071. serializationObject.matricesIndices._isExpanded = true;
  29072. }
  29073. if (this.matricesWeights) {
  29074. serializationObject.matricesWeights = this.matricesWeights;
  29075. }
  29076. if (this.matricesIndicesExtra) {
  29077. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29078. serializationObject.matricesIndicesExtra._isExpanded = true;
  29079. }
  29080. if (this.matricesWeightsExtra) {
  29081. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29082. }
  29083. serializationObject.indices = this.indices;
  29084. return serializationObject;
  29085. };
  29086. // Statics
  29087. /**
  29088. * Returns the object VertexData associated to the passed mesh.
  29089. */
  29090. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29091. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29092. };
  29093. /**
  29094. * Returns the object VertexData associated to the passed geometry.
  29095. */
  29096. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29097. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29098. };
  29099. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29100. var result = new VertexData();
  29101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29102. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29103. }
  29104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29105. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29106. }
  29107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29108. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29109. }
  29110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29111. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29112. }
  29113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29114. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29115. }
  29116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29117. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29118. }
  29119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29120. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29121. }
  29122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29123. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29124. }
  29125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29126. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29127. }
  29128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29129. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29130. }
  29131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29132. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29133. }
  29134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29135. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29136. }
  29137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29138. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29139. }
  29140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29141. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29142. }
  29143. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29144. return result;
  29145. };
  29146. /**
  29147. * Creates the vertexData of the Ribbon.
  29148. */
  29149. VertexData.CreateRibbon = function (options) {
  29150. var pathArray = options.pathArray;
  29151. var closeArray = options.closeArray || false;
  29152. var closePath = options.closePath || false;
  29153. var invertUV = options.invertUV || false;
  29154. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29155. var offset = options.offset || defaultOffset;
  29156. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29157. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29158. var customUV = options.uvs;
  29159. var customColors = options.colors;
  29160. var positions = [];
  29161. var indices = [];
  29162. var normals = [];
  29163. var uvs = [];
  29164. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29165. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29166. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29167. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29168. var minlg; // minimal length among all paths from pathArray
  29169. var lg = []; // array of path lengths : nb of vertex per path
  29170. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29171. var p; // path iterator
  29172. var i; // point iterator
  29173. var j; // point iterator
  29174. // if single path in pathArray
  29175. if (pathArray.length < 2) {
  29176. var ar1 = [];
  29177. var ar2 = [];
  29178. for (i = 0; i < pathArray[0].length - offset; i++) {
  29179. ar1.push(pathArray[0][i]);
  29180. ar2.push(pathArray[0][i + offset]);
  29181. }
  29182. pathArray = [ar1, ar2];
  29183. }
  29184. // positions and horizontal distances (u)
  29185. var idc = 0;
  29186. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29187. var path;
  29188. var l;
  29189. minlg = pathArray[0].length;
  29190. var vectlg;
  29191. var dist;
  29192. for (p = 0; p < pathArray.length; p++) {
  29193. uTotalDistance[p] = 0;
  29194. us[p] = [0];
  29195. path = pathArray[p];
  29196. l = path.length;
  29197. minlg = (minlg < l) ? minlg : l;
  29198. j = 0;
  29199. while (j < l) {
  29200. positions.push(path[j].x, path[j].y, path[j].z);
  29201. if (j > 0) {
  29202. vectlg = path[j].subtract(path[j - 1]).length();
  29203. dist = vectlg + uTotalDistance[p];
  29204. us[p].push(dist);
  29205. uTotalDistance[p] = dist;
  29206. }
  29207. j++;
  29208. }
  29209. if (closePath) {
  29210. j--;
  29211. positions.push(path[0].x, path[0].y, path[0].z);
  29212. vectlg = path[j].subtract(path[0]).length();
  29213. dist = vectlg + uTotalDistance[p];
  29214. us[p].push(dist);
  29215. uTotalDistance[p] = dist;
  29216. }
  29217. lg[p] = l + closePathCorr;
  29218. idx[p] = idc;
  29219. idc += (l + closePathCorr);
  29220. }
  29221. // vertical distances (v)
  29222. var path1;
  29223. var path2;
  29224. var vertex1 = null;
  29225. var vertex2 = null;
  29226. for (i = 0; i < minlg + closePathCorr; i++) {
  29227. vTotalDistance[i] = 0;
  29228. vs[i] = [0];
  29229. for (p = 0; p < pathArray.length - 1; p++) {
  29230. path1 = pathArray[p];
  29231. path2 = pathArray[p + 1];
  29232. if (i === minlg) {
  29233. vertex1 = path1[0];
  29234. vertex2 = path2[0];
  29235. }
  29236. else {
  29237. vertex1 = path1[i];
  29238. vertex2 = path2[i];
  29239. }
  29240. vectlg = vertex2.subtract(vertex1).length();
  29241. dist = vectlg + vTotalDistance[i];
  29242. vs[i].push(dist);
  29243. vTotalDistance[i] = dist;
  29244. }
  29245. if (closeArray && vertex2 && vertex1) {
  29246. path1 = pathArray[p];
  29247. path2 = pathArray[0];
  29248. if (i === minlg) {
  29249. vertex2 = path2[0];
  29250. }
  29251. vectlg = vertex2.subtract(vertex1).length();
  29252. dist = vectlg + vTotalDistance[i];
  29253. vTotalDistance[i] = dist;
  29254. }
  29255. }
  29256. // uvs
  29257. var u;
  29258. var v;
  29259. if (customUV) {
  29260. for (p = 0; p < customUV.length; p++) {
  29261. uvs.push(customUV[p].x, customUV[p].y);
  29262. }
  29263. }
  29264. else {
  29265. for (p = 0; p < pathArray.length; p++) {
  29266. for (i = 0; i < minlg + closePathCorr; i++) {
  29267. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29268. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29269. if (invertUV) {
  29270. uvs.push(v, u);
  29271. }
  29272. else {
  29273. uvs.push(u, v);
  29274. }
  29275. }
  29276. }
  29277. }
  29278. // indices
  29279. p = 0; // path index
  29280. var pi = 0; // positions array index
  29281. var l1 = lg[p] - 1; // path1 length
  29282. var l2 = lg[p + 1] - 1; // path2 length
  29283. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29284. var shft = idx[1] - idx[0]; // shift
  29285. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29286. while (pi <= min && p < path1nb) {
  29287. // 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
  29288. indices.push(pi, pi + shft, pi + 1);
  29289. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29290. pi += 1;
  29291. if (pi === min) {
  29292. p++;
  29293. if (p === lg.length - 1) {
  29294. shft = idx[0] - idx[p];
  29295. l1 = lg[p] - 1;
  29296. l2 = lg[0] - 1;
  29297. }
  29298. else {
  29299. shft = idx[p + 1] - idx[p];
  29300. l1 = lg[p] - 1;
  29301. l2 = lg[p + 1] - 1;
  29302. }
  29303. pi = idx[p];
  29304. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29305. }
  29306. }
  29307. // normals
  29308. VertexData.ComputeNormals(positions, indices, normals);
  29309. if (closePath) {
  29310. var indexFirst = 0;
  29311. var indexLast = 0;
  29312. for (p = 0; p < pathArray.length; p++) {
  29313. indexFirst = idx[p] * 3;
  29314. if (p + 1 < pathArray.length) {
  29315. indexLast = (idx[p + 1] - 1) * 3;
  29316. }
  29317. else {
  29318. indexLast = normals.length - 3;
  29319. }
  29320. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29321. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29322. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29323. normals[indexLast] = normals[indexFirst];
  29324. normals[indexLast + 1] = normals[indexFirst + 1];
  29325. normals[indexLast + 2] = normals[indexFirst + 2];
  29326. }
  29327. }
  29328. // sides
  29329. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29330. // Colors
  29331. var colors = null;
  29332. if (customColors) {
  29333. colors = new Float32Array(customColors.length * 4);
  29334. for (var c = 0; c < customColors.length; c++) {
  29335. colors[c * 4] = customColors[c].r;
  29336. colors[c * 4 + 1] = customColors[c].g;
  29337. colors[c * 4 + 2] = customColors[c].b;
  29338. colors[c * 4 + 3] = customColors[c].a;
  29339. }
  29340. }
  29341. // Result
  29342. var vertexData = new VertexData();
  29343. var positions32 = new Float32Array(positions);
  29344. var normals32 = new Float32Array(normals);
  29345. var uvs32 = new Float32Array(uvs);
  29346. vertexData.indices = indices;
  29347. vertexData.positions = positions32;
  29348. vertexData.normals = normals32;
  29349. vertexData.uvs = uvs32;
  29350. if (colors) {
  29351. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29352. }
  29353. if (closePath) {
  29354. vertexData._idx = idx;
  29355. }
  29356. return vertexData;
  29357. };
  29358. /**
  29359. * Creates the VertexData of the Box.
  29360. */
  29361. VertexData.CreateBox = function (options) {
  29362. var normalsSource = [
  29363. new BABYLON.Vector3(0, 0, 1),
  29364. new BABYLON.Vector3(0, 0, -1),
  29365. new BABYLON.Vector3(1, 0, 0),
  29366. new BABYLON.Vector3(-1, 0, 0),
  29367. new BABYLON.Vector3(0, 1, 0),
  29368. new BABYLON.Vector3(0, -1, 0)
  29369. ];
  29370. var indices = [];
  29371. var positions = [];
  29372. var normals = [];
  29373. var uvs = [];
  29374. var width = options.width || options.size || 1;
  29375. var height = options.height || options.size || 1;
  29376. var depth = options.depth || options.size || 1;
  29377. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29378. var faceUV = options.faceUV || new Array(6);
  29379. var faceColors = options.faceColors;
  29380. var colors = [];
  29381. // default face colors and UV if undefined
  29382. for (var f = 0; f < 6; f++) {
  29383. if (faceUV[f] === undefined) {
  29384. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29385. }
  29386. if (faceColors && faceColors[f] === undefined) {
  29387. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29388. }
  29389. }
  29390. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29391. // Create each face in turn.
  29392. for (var index = 0; index < normalsSource.length; index++) {
  29393. var normal = normalsSource[index];
  29394. // Get two vectors perpendicular to the face normal and to each other.
  29395. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29396. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29397. // Six indices (two triangles) per face.
  29398. var verticesLength = positions.length / 3;
  29399. indices.push(verticesLength);
  29400. indices.push(verticesLength + 1);
  29401. indices.push(verticesLength + 2);
  29402. indices.push(verticesLength);
  29403. indices.push(verticesLength + 2);
  29404. indices.push(verticesLength + 3);
  29405. // Four vertices per face.
  29406. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29407. positions.push(vertex.x, vertex.y, vertex.z);
  29408. normals.push(normal.x, normal.y, normal.z);
  29409. uvs.push(faceUV[index].z, faceUV[index].w);
  29410. if (faceColors) {
  29411. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29412. }
  29413. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29414. positions.push(vertex.x, vertex.y, vertex.z);
  29415. normals.push(normal.x, normal.y, normal.z);
  29416. uvs.push(faceUV[index].x, faceUV[index].w);
  29417. if (faceColors) {
  29418. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29419. }
  29420. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29421. positions.push(vertex.x, vertex.y, vertex.z);
  29422. normals.push(normal.x, normal.y, normal.z);
  29423. uvs.push(faceUV[index].x, faceUV[index].y);
  29424. if (faceColors) {
  29425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29426. }
  29427. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29428. positions.push(vertex.x, vertex.y, vertex.z);
  29429. normals.push(normal.x, normal.y, normal.z);
  29430. uvs.push(faceUV[index].z, faceUV[index].y);
  29431. if (faceColors) {
  29432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29433. }
  29434. }
  29435. // sides
  29436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29437. // Result
  29438. var vertexData = new VertexData();
  29439. vertexData.indices = indices;
  29440. vertexData.positions = positions;
  29441. vertexData.normals = normals;
  29442. vertexData.uvs = uvs;
  29443. if (faceColors) {
  29444. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29445. vertexData.colors = totalColors;
  29446. }
  29447. return vertexData;
  29448. };
  29449. /**
  29450. * Creates the VertexData of the Sphere.
  29451. */
  29452. VertexData.CreateSphere = function (options) {
  29453. var segments = options.segments || 32;
  29454. var diameterX = options.diameterX || options.diameter || 1;
  29455. var diameterY = options.diameterY || options.diameter || 1;
  29456. var diameterZ = options.diameterZ || options.diameter || 1;
  29457. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29458. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29459. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29460. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29461. var totalZRotationSteps = 2 + segments;
  29462. var totalYRotationSteps = 2 * totalZRotationSteps;
  29463. var indices = [];
  29464. var positions = [];
  29465. var normals = [];
  29466. var uvs = [];
  29467. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29468. var normalizedZ = zRotationStep / totalZRotationSteps;
  29469. var angleZ = normalizedZ * Math.PI * slice;
  29470. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29471. var normalizedY = yRotationStep / totalYRotationSteps;
  29472. var angleY = normalizedY * Math.PI * 2 * arc;
  29473. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29474. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29475. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29476. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29477. var vertex = complete.multiply(radius);
  29478. var normal = complete.divide(radius).normalize();
  29479. positions.push(vertex.x, vertex.y, vertex.z);
  29480. normals.push(normal.x, normal.y, normal.z);
  29481. uvs.push(normalizedY, normalizedZ);
  29482. }
  29483. if (zRotationStep > 0) {
  29484. var verticesCount = positions.length / 3;
  29485. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29486. indices.push((firstIndex));
  29487. indices.push((firstIndex + 1));
  29488. indices.push(firstIndex + totalYRotationSteps + 1);
  29489. indices.push((firstIndex + totalYRotationSteps + 1));
  29490. indices.push((firstIndex + 1));
  29491. indices.push((firstIndex + totalYRotationSteps + 2));
  29492. }
  29493. }
  29494. }
  29495. // Sides
  29496. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29497. // Result
  29498. var vertexData = new VertexData();
  29499. vertexData.indices = indices;
  29500. vertexData.positions = positions;
  29501. vertexData.normals = normals;
  29502. vertexData.uvs = uvs;
  29503. return vertexData;
  29504. };
  29505. /**
  29506. * Creates the VertexData of the Cylinder or Cone.
  29507. */
  29508. VertexData.CreateCylinder = function (options) {
  29509. var height = options.height || 2;
  29510. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29511. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29512. var tessellation = options.tessellation || 24;
  29513. var subdivisions = options.subdivisions || 1;
  29514. var hasRings = options.hasRings ? true : false;
  29515. var enclose = options.enclose ? true : false;
  29516. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29518. var faceUV = options.faceUV || new Array(3);
  29519. var faceColors = options.faceColors;
  29520. // default face colors and UV if undefined
  29521. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29522. var ringNb = (hasRings) ? subdivisions : 1;
  29523. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29524. var f;
  29525. for (f = 0; f < surfaceNb; f++) {
  29526. if (faceColors && faceColors[f] === undefined) {
  29527. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29528. }
  29529. }
  29530. for (f = 0; f < surfaceNb; f++) {
  29531. if (faceUV && faceUV[f] === undefined) {
  29532. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29533. }
  29534. }
  29535. var indices = new Array();
  29536. var positions = new Array();
  29537. var normals = new Array();
  29538. var uvs = new Array();
  29539. var colors = new Array();
  29540. var angle_step = Math.PI * 2 * arc / tessellation;
  29541. var angle;
  29542. var h;
  29543. var radius;
  29544. var tan = (diameterBottom - diameterTop) / 2 / height;
  29545. var ringVertex = BABYLON.Vector3.Zero();
  29546. var ringNormal = BABYLON.Vector3.Zero();
  29547. var ringFirstVertex = BABYLON.Vector3.Zero();
  29548. var ringFirstNormal = BABYLON.Vector3.Zero();
  29549. var quadNormal = BABYLON.Vector3.Zero();
  29550. var Y = BABYLON.Axis.Y;
  29551. // positions, normals, uvs
  29552. var i;
  29553. var j;
  29554. var r;
  29555. var ringIdx = 1;
  29556. var s = 1; // surface index
  29557. var cs = 0;
  29558. var v = 0;
  29559. for (i = 0; i <= subdivisions; i++) {
  29560. h = i / subdivisions;
  29561. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29562. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29563. for (r = 0; r < ringIdx; r++) {
  29564. if (hasRings) {
  29565. s += r;
  29566. }
  29567. if (enclose) {
  29568. s += 2 * r;
  29569. }
  29570. for (j = 0; j <= tessellation; j++) {
  29571. angle = j * angle_step;
  29572. // position
  29573. ringVertex.x = Math.cos(-angle) * radius;
  29574. ringVertex.y = -height / 2 + h * height;
  29575. ringVertex.z = Math.sin(-angle) * radius;
  29576. // normal
  29577. if (diameterTop === 0 && i === subdivisions) {
  29578. // if no top cap, reuse former normals
  29579. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29580. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29581. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29582. }
  29583. else {
  29584. ringNormal.x = ringVertex.x;
  29585. ringNormal.z = ringVertex.z;
  29586. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29587. ringNormal.normalize();
  29588. }
  29589. // keep first ring vertex values for enclose
  29590. if (j === 0) {
  29591. ringFirstVertex.copyFrom(ringVertex);
  29592. ringFirstNormal.copyFrom(ringNormal);
  29593. }
  29594. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29595. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29596. if (hasRings) {
  29597. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29598. }
  29599. else {
  29600. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29601. }
  29602. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29603. if (faceColors) {
  29604. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29605. }
  29606. }
  29607. // if enclose, add four vertices and their dedicated normals
  29608. if (arc !== 1 && enclose) {
  29609. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29610. positions.push(0, ringVertex.y, 0);
  29611. positions.push(0, ringVertex.y, 0);
  29612. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29613. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29614. quadNormal.normalize();
  29615. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29616. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29617. quadNormal.normalize();
  29618. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29619. if (hasRings) {
  29620. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29621. }
  29622. else {
  29623. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29624. }
  29625. uvs.push(faceUV[s + 1].x, v);
  29626. uvs.push(faceUV[s + 1].z, v);
  29627. if (hasRings) {
  29628. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29629. }
  29630. else {
  29631. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29632. }
  29633. uvs.push(faceUV[s + 2].x, v);
  29634. uvs.push(faceUV[s + 2].z, v);
  29635. if (faceColors) {
  29636. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29637. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29638. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29639. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29640. }
  29641. }
  29642. if (cs !== s) {
  29643. cs = s;
  29644. }
  29645. }
  29646. }
  29647. // indices
  29648. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29649. var s;
  29650. i = 0;
  29651. for (s = 0; s < subdivisions; s++) {
  29652. var i0 = 0;
  29653. var i1 = 0;
  29654. var i2 = 0;
  29655. var i3 = 0;
  29656. for (j = 0; j < tessellation; j++) {
  29657. i0 = i * (e + 1) + j;
  29658. i1 = (i + 1) * (e + 1) + j;
  29659. i2 = i * (e + 1) + (j + 1);
  29660. i3 = (i + 1) * (e + 1) + (j + 1);
  29661. indices.push(i0, i1, i2);
  29662. indices.push(i3, i2, i1);
  29663. }
  29664. if (arc !== 1 && enclose) {
  29665. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29666. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29667. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29668. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29669. }
  29670. i = (hasRings) ? (i + 2) : (i + 1);
  29671. }
  29672. // Caps
  29673. var createCylinderCap = function (isTop) {
  29674. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29675. if (radius === 0) {
  29676. return;
  29677. }
  29678. // Cap positions, normals & uvs
  29679. var angle;
  29680. var circleVector;
  29681. var i;
  29682. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29683. var c = null;
  29684. if (faceColors) {
  29685. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29686. }
  29687. // cap center
  29688. var vbase = positions.length / 3;
  29689. var offset = isTop ? height / 2 : -height / 2;
  29690. var center = new BABYLON.Vector3(0, offset, 0);
  29691. positions.push(center.x, center.y, center.z);
  29692. normals.push(0, isTop ? 1 : -1, 0);
  29693. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29694. if (c) {
  29695. colors.push(c.r, c.g, c.b, c.a);
  29696. }
  29697. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29698. for (i = 0; i <= tessellation; i++) {
  29699. angle = Math.PI * 2 * i * arc / tessellation;
  29700. var cos = Math.cos(-angle);
  29701. var sin = Math.sin(-angle);
  29702. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29703. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29704. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29705. normals.push(0, isTop ? 1 : -1, 0);
  29706. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29707. if (c) {
  29708. colors.push(c.r, c.g, c.b, c.a);
  29709. }
  29710. }
  29711. // Cap indices
  29712. for (i = 0; i < tessellation; i++) {
  29713. if (!isTop) {
  29714. indices.push(vbase);
  29715. indices.push(vbase + (i + 1));
  29716. indices.push(vbase + (i + 2));
  29717. }
  29718. else {
  29719. indices.push(vbase);
  29720. indices.push(vbase + (i + 2));
  29721. indices.push(vbase + (i + 1));
  29722. }
  29723. }
  29724. };
  29725. // add caps to geometry
  29726. createCylinderCap(false);
  29727. createCylinderCap(true);
  29728. // Sides
  29729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29730. var vertexData = new VertexData();
  29731. vertexData.indices = indices;
  29732. vertexData.positions = positions;
  29733. vertexData.normals = normals;
  29734. vertexData.uvs = uvs;
  29735. if (faceColors) {
  29736. vertexData.colors = colors;
  29737. }
  29738. return vertexData;
  29739. };
  29740. /**
  29741. * Creates the VertexData of the Torus.
  29742. */
  29743. VertexData.CreateTorus = function (options) {
  29744. var indices = [];
  29745. var positions = [];
  29746. var normals = [];
  29747. var uvs = [];
  29748. var diameter = options.diameter || 1;
  29749. var thickness = options.thickness || 0.5;
  29750. var tessellation = options.tessellation || 16;
  29751. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29752. var stride = tessellation + 1;
  29753. for (var i = 0; i <= tessellation; i++) {
  29754. var u = i / tessellation;
  29755. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29756. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29757. for (var j = 0; j <= tessellation; j++) {
  29758. var v = 1 - j / tessellation;
  29759. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29760. var dx = Math.cos(innerAngle);
  29761. var dy = Math.sin(innerAngle);
  29762. // Create a vertex.
  29763. var normal = new BABYLON.Vector3(dx, dy, 0);
  29764. var position = normal.scale(thickness / 2);
  29765. var textureCoordinate = new BABYLON.Vector2(u, v);
  29766. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29767. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29768. positions.push(position.x, position.y, position.z);
  29769. normals.push(normal.x, normal.y, normal.z);
  29770. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29771. // And create indices for two triangles.
  29772. var nextI = (i + 1) % stride;
  29773. var nextJ = (j + 1) % stride;
  29774. indices.push(i * stride + j);
  29775. indices.push(i * stride + nextJ);
  29776. indices.push(nextI * stride + j);
  29777. indices.push(i * stride + nextJ);
  29778. indices.push(nextI * stride + nextJ);
  29779. indices.push(nextI * stride + j);
  29780. }
  29781. }
  29782. // Sides
  29783. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29784. // Result
  29785. var vertexData = new VertexData();
  29786. vertexData.indices = indices;
  29787. vertexData.positions = positions;
  29788. vertexData.normals = normals;
  29789. vertexData.uvs = uvs;
  29790. return vertexData;
  29791. };
  29792. /**
  29793. * Creates the VertexData of the LineSystem.
  29794. */
  29795. VertexData.CreateLineSystem = function (options) {
  29796. var indices = [];
  29797. var positions = [];
  29798. var lines = options.lines;
  29799. var colors = options.colors;
  29800. var vertexColors = [];
  29801. var idx = 0;
  29802. for (var l = 0; l < lines.length; l++) {
  29803. var points = lines[l];
  29804. for (var index = 0; index < points.length; index++) {
  29805. positions.push(points[index].x, points[index].y, points[index].z);
  29806. if (colors) {
  29807. var color = colors[l];
  29808. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29809. }
  29810. if (index > 0) {
  29811. indices.push(idx - 1);
  29812. indices.push(idx);
  29813. }
  29814. idx++;
  29815. }
  29816. }
  29817. var vertexData = new VertexData();
  29818. vertexData.indices = indices;
  29819. vertexData.positions = positions;
  29820. if (colors) {
  29821. vertexData.colors = vertexColors;
  29822. }
  29823. return vertexData;
  29824. };
  29825. /**
  29826. * Create the VertexData of the DashedLines.
  29827. */
  29828. VertexData.CreateDashedLines = function (options) {
  29829. var dashSize = options.dashSize || 3;
  29830. var gapSize = options.gapSize || 1;
  29831. var dashNb = options.dashNb || 200;
  29832. var points = options.points;
  29833. var positions = new Array();
  29834. var indices = new Array();
  29835. var curvect = BABYLON.Vector3.Zero();
  29836. var lg = 0;
  29837. var nb = 0;
  29838. var shft = 0;
  29839. var dashshft = 0;
  29840. var curshft = 0;
  29841. var idx = 0;
  29842. var i = 0;
  29843. for (i = 0; i < points.length - 1; i++) {
  29844. points[i + 1].subtractToRef(points[i], curvect);
  29845. lg += curvect.length();
  29846. }
  29847. shft = lg / dashNb;
  29848. dashshft = dashSize * shft / (dashSize + gapSize);
  29849. for (i = 0; i < points.length - 1; i++) {
  29850. points[i + 1].subtractToRef(points[i], curvect);
  29851. nb = Math.floor(curvect.length() / shft);
  29852. curvect.normalize();
  29853. for (var j = 0; j < nb; j++) {
  29854. curshft = shft * j;
  29855. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29856. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29857. indices.push(idx, idx + 1);
  29858. idx += 2;
  29859. }
  29860. }
  29861. // Result
  29862. var vertexData = new VertexData();
  29863. vertexData.positions = positions;
  29864. vertexData.indices = indices;
  29865. return vertexData;
  29866. };
  29867. /**
  29868. * Creates the VertexData of the Ground.
  29869. */
  29870. VertexData.CreateGround = function (options) {
  29871. var indices = [];
  29872. var positions = [];
  29873. var normals = [];
  29874. var uvs = [];
  29875. var row, col;
  29876. var width = options.width || 1;
  29877. var height = options.height || 1;
  29878. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29879. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29880. for (row = 0; row <= subdivisionsY; row++) {
  29881. for (col = 0; col <= subdivisionsX; col++) {
  29882. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29883. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29884. positions.push(position.x, position.y, position.z);
  29885. normals.push(normal.x, normal.y, normal.z);
  29886. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29887. }
  29888. }
  29889. for (row = 0; row < subdivisionsY; row++) {
  29890. for (col = 0; col < subdivisionsX; col++) {
  29891. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29892. indices.push(col + 1 + row * (subdivisionsX + 1));
  29893. indices.push(col + row * (subdivisionsX + 1));
  29894. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29895. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29896. indices.push(col + row * (subdivisionsX + 1));
  29897. }
  29898. }
  29899. // Result
  29900. var vertexData = new VertexData();
  29901. vertexData.indices = indices;
  29902. vertexData.positions = positions;
  29903. vertexData.normals = normals;
  29904. vertexData.uvs = uvs;
  29905. return vertexData;
  29906. };
  29907. /**
  29908. * Creates the VertexData of the TiledGround.
  29909. */
  29910. VertexData.CreateTiledGround = function (options) {
  29911. var xmin = options.xmin || -1.0;
  29912. var zmin = options.zmin || -1.0;
  29913. var xmax = options.xmax || 1.0;
  29914. var zmax = options.zmax || 1.0;
  29915. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29916. var precision = options.precision || { w: 1, h: 1 };
  29917. var indices = new Array();
  29918. var positions = new Array();
  29919. var normals = new Array();
  29920. var uvs = new Array();
  29921. var row, col, tileRow, tileCol;
  29922. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29923. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29924. precision.w = (precision.w < 1) ? 1 : precision.w;
  29925. precision.h = (precision.h < 1) ? 1 : precision.h;
  29926. var tileSize = {
  29927. 'w': (xmax - xmin) / subdivisions.w,
  29928. 'h': (zmax - zmin) / subdivisions.h
  29929. };
  29930. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29931. // Indices
  29932. var base = positions.length / 3;
  29933. var rowLength = precision.w + 1;
  29934. for (row = 0; row < precision.h; row++) {
  29935. for (col = 0; col < precision.w; col++) {
  29936. var square = [
  29937. base + col + row * rowLength,
  29938. base + (col + 1) + row * rowLength,
  29939. base + (col + 1) + (row + 1) * rowLength,
  29940. base + col + (row + 1) * rowLength
  29941. ];
  29942. indices.push(square[1]);
  29943. indices.push(square[2]);
  29944. indices.push(square[3]);
  29945. indices.push(square[0]);
  29946. indices.push(square[1]);
  29947. indices.push(square[3]);
  29948. }
  29949. }
  29950. // Position, normals and uvs
  29951. var position = BABYLON.Vector3.Zero();
  29952. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29953. for (row = 0; row <= precision.h; row++) {
  29954. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29955. for (col = 0; col <= precision.w; col++) {
  29956. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29957. position.y = 0;
  29958. positions.push(position.x, position.y, position.z);
  29959. normals.push(normal.x, normal.y, normal.z);
  29960. uvs.push(col / precision.w, row / precision.h);
  29961. }
  29962. }
  29963. }
  29964. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29965. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29966. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29967. }
  29968. }
  29969. // Result
  29970. var vertexData = new VertexData();
  29971. vertexData.indices = indices;
  29972. vertexData.positions = positions;
  29973. vertexData.normals = normals;
  29974. vertexData.uvs = uvs;
  29975. return vertexData;
  29976. };
  29977. /**
  29978. * Creates the VertexData of the Ground designed from a heightmap.
  29979. */
  29980. VertexData.CreateGroundFromHeightMap = function (options) {
  29981. var indices = [];
  29982. var positions = [];
  29983. var normals = [];
  29984. var uvs = [];
  29985. var row, col;
  29986. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29987. // Vertices
  29988. for (row = 0; row <= options.subdivisions; row++) {
  29989. for (col = 0; col <= options.subdivisions; col++) {
  29990. 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));
  29991. // Compute height
  29992. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29993. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29994. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29995. var r = options.buffer[pos] / 255.0;
  29996. var g = options.buffer[pos + 1] / 255.0;
  29997. var b = options.buffer[pos + 2] / 255.0;
  29998. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29999. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30000. // Add vertex
  30001. positions.push(position.x, position.y, position.z);
  30002. normals.push(0, 0, 0);
  30003. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30004. }
  30005. }
  30006. // Indices
  30007. for (row = 0; row < options.subdivisions; row++) {
  30008. for (col = 0; col < options.subdivisions; col++) {
  30009. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30010. indices.push(col + 1 + row * (options.subdivisions + 1));
  30011. indices.push(col + row * (options.subdivisions + 1));
  30012. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30013. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30014. indices.push(col + row * (options.subdivisions + 1));
  30015. }
  30016. }
  30017. // Normals
  30018. VertexData.ComputeNormals(positions, indices, normals);
  30019. // Result
  30020. var vertexData = new VertexData();
  30021. vertexData.indices = indices;
  30022. vertexData.positions = positions;
  30023. vertexData.normals = normals;
  30024. vertexData.uvs = uvs;
  30025. return vertexData;
  30026. };
  30027. /**
  30028. * Creates the VertexData of the Plane.
  30029. */
  30030. VertexData.CreatePlane = function (options) {
  30031. var indices = [];
  30032. var positions = [];
  30033. var normals = [];
  30034. var uvs = [];
  30035. var width = options.width || options.size || 1;
  30036. var height = options.height || options.size || 1;
  30037. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30038. // Vertices
  30039. var halfWidth = width / 2.0;
  30040. var halfHeight = height / 2.0;
  30041. positions.push(-halfWidth, -halfHeight, 0);
  30042. normals.push(0, 0, -1.0);
  30043. uvs.push(0.0, 0.0);
  30044. positions.push(halfWidth, -halfHeight, 0);
  30045. normals.push(0, 0, -1.0);
  30046. uvs.push(1.0, 0.0);
  30047. positions.push(halfWidth, halfHeight, 0);
  30048. normals.push(0, 0, -1.0);
  30049. uvs.push(1.0, 1.0);
  30050. positions.push(-halfWidth, halfHeight, 0);
  30051. normals.push(0, 0, -1.0);
  30052. uvs.push(0.0, 1.0);
  30053. // Indices
  30054. indices.push(0);
  30055. indices.push(1);
  30056. indices.push(2);
  30057. indices.push(0);
  30058. indices.push(2);
  30059. indices.push(3);
  30060. // Sides
  30061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30062. // Result
  30063. var vertexData = new VertexData();
  30064. vertexData.indices = indices;
  30065. vertexData.positions = positions;
  30066. vertexData.normals = normals;
  30067. vertexData.uvs = uvs;
  30068. return vertexData;
  30069. };
  30070. /**
  30071. * Creates the VertexData of the Disc or regular Polygon.
  30072. */
  30073. VertexData.CreateDisc = function (options) {
  30074. var positions = new Array();
  30075. var indices = new Array();
  30076. var normals = new Array();
  30077. var uvs = new Array();
  30078. var radius = options.radius || 0.5;
  30079. var tessellation = options.tessellation || 64;
  30080. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30081. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30082. // positions and uvs
  30083. positions.push(0, 0, 0); // disc center first
  30084. uvs.push(0.5, 0.5);
  30085. var theta = Math.PI * 2 * arc;
  30086. var step = theta / tessellation;
  30087. for (var a = 0; a < theta; a += step) {
  30088. var x = Math.cos(a);
  30089. var y = Math.sin(a);
  30090. var u = (x + 1) / 2;
  30091. var v = (1 - y) / 2;
  30092. positions.push(radius * x, radius * y, 0);
  30093. uvs.push(u, v);
  30094. }
  30095. if (arc === 1) {
  30096. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30097. uvs.push(uvs[2], uvs[3]);
  30098. }
  30099. //indices
  30100. var vertexNb = positions.length / 3;
  30101. for (var i = 1; i < vertexNb - 1; i++) {
  30102. indices.push(i + 1, 0, i);
  30103. }
  30104. // result
  30105. VertexData.ComputeNormals(positions, indices, normals);
  30106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30107. var vertexData = new VertexData();
  30108. vertexData.indices = indices;
  30109. vertexData.positions = positions;
  30110. vertexData.normals = normals;
  30111. vertexData.uvs = uvs;
  30112. return vertexData;
  30113. };
  30114. /**
  30115. * Re-creates the VertexData of the Polygon for sideOrientation.
  30116. */
  30117. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30118. var faceUV = fUV || new Array(3);
  30119. var faceColors = fColors;
  30120. var colors = [];
  30121. // default face colors and UV if undefined
  30122. for (var f = 0; f < 3; f++) {
  30123. if (faceUV[f] === undefined) {
  30124. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30125. }
  30126. if (faceColors && faceColors[f] === undefined) {
  30127. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30128. }
  30129. }
  30130. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30131. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30132. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30133. var indices = polygon.getIndices();
  30134. // set face colours and textures
  30135. var idx = 0;
  30136. var face = 0;
  30137. for (var index = 0; index < normals.length; index += 3) {
  30138. //Edge Face no. 1
  30139. if (Math.abs(normals[index + 1]) < 0.001) {
  30140. face = 1;
  30141. }
  30142. //Top Face no. 0
  30143. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30144. face = 0;
  30145. }
  30146. //Bottom Face no. 2
  30147. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30148. face = 2;
  30149. }
  30150. idx = index / 3;
  30151. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30152. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30153. if (faceColors) {
  30154. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30155. }
  30156. }
  30157. // sides
  30158. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30159. // Result
  30160. var vertexData = new VertexData();
  30161. vertexData.indices = indices;
  30162. vertexData.positions = positions;
  30163. vertexData.normals = normals;
  30164. vertexData.uvs = uvs;
  30165. if (faceColors) {
  30166. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30167. vertexData.colors = totalColors;
  30168. }
  30169. return vertexData;
  30170. };
  30171. /**
  30172. * Creates the VertexData of the IcoSphere.
  30173. */
  30174. VertexData.CreateIcoSphere = function (options) {
  30175. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30176. var radius = options.radius || 1;
  30177. var flat = (options.flat === undefined) ? true : options.flat;
  30178. var subdivisions = options.subdivisions || 4;
  30179. var radiusX = options.radiusX || radius;
  30180. var radiusY = options.radiusY || radius;
  30181. var radiusZ = options.radiusZ || radius;
  30182. var t = (1 + Math.sqrt(5)) / 2;
  30183. // 12 vertex x,y,z
  30184. var ico_vertices = [
  30185. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30186. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30187. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30188. ];
  30189. // index of 3 vertex makes a face of icopshere
  30190. var ico_indices = [
  30191. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30192. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30193. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30194. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30195. ];
  30196. // vertex for uv have aliased position, not for UV
  30197. var vertices_unalias_id = [
  30198. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30199. // vertex alias
  30200. 0,
  30201. 2,
  30202. 3,
  30203. 3,
  30204. 3,
  30205. 4,
  30206. 7,
  30207. 8,
  30208. 9,
  30209. 9,
  30210. 10,
  30211. 11 // 23: B + 12
  30212. ];
  30213. // uv as integer step (not pixels !)
  30214. var ico_vertexuv = [
  30215. 5, 1, 3, 1, 6, 4, 0, 0,
  30216. 5, 3, 4, 2, 2, 2, 4, 0,
  30217. 2, 0, 1, 1, 6, 0, 6, 2,
  30218. // vertex alias (for same vertex on different faces)
  30219. 0, 4,
  30220. 3, 3,
  30221. 4, 4,
  30222. 3, 1,
  30223. 4, 2,
  30224. 4, 4,
  30225. 0, 2,
  30226. 1, 1,
  30227. 2, 2,
  30228. 3, 3,
  30229. 1, 3,
  30230. 2, 4 // 23: B + 12
  30231. ];
  30232. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30233. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30234. // First island of uv mapping
  30235. // v = 4h 3+ 2
  30236. // v = 3h 9+ 4
  30237. // v = 2h 9+ 5 B
  30238. // v = 1h 9 1 0
  30239. // v = 0h 3 8 7 A
  30240. // u = 0 1 2 3 4 5 6 *a
  30241. // Second island of uv mapping
  30242. // v = 4h 0+ B+ 4+
  30243. // v = 3h A+ 2+
  30244. // v = 2h 7+ 6 3+
  30245. // v = 1h 8+ 3+
  30246. // v = 0h
  30247. // u = 0 1 2 3 4 5 6 *a
  30248. // Face layout on texture UV mapping
  30249. // ============
  30250. // \ 4 /\ 16 / ======
  30251. // \ / \ / /\ 11 /
  30252. // \/ 7 \/ / \ /
  30253. // ======= / 10 \/
  30254. // /\ 17 /\ =======
  30255. // / \ / \ \ 15 /\
  30256. // / 8 \/ 12 \ \ / \
  30257. // ============ \/ 6 \
  30258. // \ 18 /\ ============
  30259. // \ / \ \ 5 /\ 0 /
  30260. // \/ 13 \ \ / \ /
  30261. // ======= \/ 1 \/
  30262. // =============
  30263. // /\ 19 /\ 2 /\
  30264. // / \ / \ / \
  30265. // / 14 \/ 9 \/ 3 \
  30266. // ===================
  30267. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30268. var ustep = 138 / 1024;
  30269. var vstep = 239 / 1024;
  30270. var uoffset = 60 / 1024;
  30271. var voffset = 26 / 1024;
  30272. // Second island should have margin, not to touch the first island
  30273. // avoid any borderline artefact in pixel rounding
  30274. var island_u_offset = -40 / 1024;
  30275. var island_v_offset = +20 / 1024;
  30276. // face is either island 0 or 1 :
  30277. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30278. var island = [
  30279. 0, 0, 0, 0, 1,
  30280. 0, 0, 1, 1, 0,
  30281. 0, 0, 1, 1, 0,
  30282. 0, 1, 1, 1, 0 // 15 - 19
  30283. ];
  30284. var indices = new Array();
  30285. var positions = new Array();
  30286. var normals = new Array();
  30287. var uvs = new Array();
  30288. var current_indice = 0;
  30289. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30290. var face_vertex_pos = new Array(3);
  30291. var face_vertex_uv = new Array(3);
  30292. var v012;
  30293. for (v012 = 0; v012 < 3; v012++) {
  30294. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30295. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30296. }
  30297. // create all with normals
  30298. for (var face = 0; face < 20; face++) {
  30299. // 3 vertex per face
  30300. for (v012 = 0; v012 < 3; v012++) {
  30301. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30302. var v_id = ico_indices[3 * face + v012];
  30303. // vertex have 3D position (x,y,z)
  30304. 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]);
  30305. // Normalize to get normal, then scale to radius
  30306. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30307. // uv Coordinates from vertex ID
  30308. 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);
  30309. }
  30310. // Subdivide the face (interpolate pos, norm, uv)
  30311. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30312. // - norm is linear interpolation of vertex corner normal
  30313. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30314. // - uv is linear interpolation
  30315. //
  30316. // Topology is as below for sub-divide by 2
  30317. // vertex shown as v0,v1,v2
  30318. // interp index is i1 to progress in range [v0,v1[
  30319. // interp index is i2 to progress in range [v0,v2[
  30320. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30321. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30322. //
  30323. //
  30324. // i2 v2
  30325. // ^ ^
  30326. // / / \
  30327. // / / \
  30328. // / / \
  30329. // / / (0,1) \
  30330. // / #---------\
  30331. // / / \ (0,0)'/ \
  30332. // / / \ / \
  30333. // / / \ / \
  30334. // / / (0,0) \ / (1,0) \
  30335. // / #---------#---------\
  30336. // v0 v1
  30337. //
  30338. // --------------------> i1
  30339. //
  30340. // interp of (i1,i2):
  30341. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30342. // along i1 : lerp(x0,x1, i1/(S-i2))
  30343. //
  30344. // centroid of triangle is needed to get help normal computation
  30345. // (c1,c2) are used for centroid location
  30346. var interp_vertex = function (i1, i2, c1, c2) {
  30347. // vertex is interpolated from
  30348. // - face_vertex_pos[0..2]
  30349. // - face_vertex_uv[0..2]
  30350. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30351. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30352. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30353. pos_interp.normalize();
  30354. var vertex_normal;
  30355. if (flat) {
  30356. // in flat mode, recalculate normal as face centroid normal
  30357. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30358. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30359. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30360. }
  30361. else {
  30362. // in smooth mode, recalculate normal from each single vertex position
  30363. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30364. }
  30365. // Vertex normal need correction due to X,Y,Z radius scaling
  30366. vertex_normal.x /= radiusX;
  30367. vertex_normal.y /= radiusY;
  30368. vertex_normal.z /= radiusZ;
  30369. vertex_normal.normalize();
  30370. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30371. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30372. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30373. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30374. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30375. uvs.push(uv_interp.x, uv_interp.y);
  30376. // push each vertex has member of a face
  30377. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30378. indices.push(current_indice);
  30379. current_indice++;
  30380. };
  30381. for (var i2 = 0; i2 < subdivisions; i2++) {
  30382. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30383. // face : (i1,i2) for /\ :
  30384. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30385. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30386. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30387. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30388. if (i1 + i2 + 1 < subdivisions) {
  30389. // face : (i1,i2)' for \/ :
  30390. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30391. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30392. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30393. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30394. }
  30395. }
  30396. }
  30397. }
  30398. // Sides
  30399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30400. // Result
  30401. var vertexData = new VertexData();
  30402. vertexData.indices = indices;
  30403. vertexData.positions = positions;
  30404. vertexData.normals = normals;
  30405. vertexData.uvs = uvs;
  30406. return vertexData;
  30407. };
  30408. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30409. /**
  30410. * Creates the VertexData of the Polyhedron.
  30411. */
  30412. VertexData.CreatePolyhedron = function (options) {
  30413. // provided polyhedron types :
  30414. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30415. // 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)
  30416. var polyhedra = [];
  30417. 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]] };
  30418. 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]] };
  30419. polyhedra[2] = {
  30420. 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]],
  30421. 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]]
  30422. };
  30423. polyhedra[3] = {
  30424. 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]],
  30425. 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]]
  30426. };
  30427. polyhedra[4] = {
  30428. 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]],
  30429. 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]]
  30430. };
  30431. 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]] };
  30432. 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]] };
  30433. 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]] };
  30434. 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]] };
  30435. 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]] };
  30436. 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]] };
  30437. 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]] };
  30438. 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]] };
  30439. 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]] };
  30440. polyhedra[14] = {
  30441. 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]],
  30442. 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]]
  30443. };
  30444. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30445. var size = options.size;
  30446. var sizeX = options.sizeX || size || 1;
  30447. var sizeY = options.sizeY || size || 1;
  30448. var sizeZ = options.sizeZ || size || 1;
  30449. var data = options.custom || polyhedra[type];
  30450. var nbfaces = data.face.length;
  30451. var faceUV = options.faceUV || new Array(nbfaces);
  30452. var faceColors = options.faceColors;
  30453. var flat = (options.flat === undefined) ? true : options.flat;
  30454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30455. var positions = new Array();
  30456. var indices = new Array();
  30457. var normals = new Array();
  30458. var uvs = new Array();
  30459. var colors = new Array();
  30460. var index = 0;
  30461. var faceIdx = 0; // face cursor in the array "indexes"
  30462. var indexes = new Array();
  30463. var i = 0;
  30464. var f = 0;
  30465. var u, v, ang, x, y, tmp;
  30466. // default face colors and UV if undefined
  30467. if (flat) {
  30468. for (f = 0; f < nbfaces; f++) {
  30469. if (faceColors && faceColors[f] === undefined) {
  30470. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30471. }
  30472. if (faceUV && faceUV[f] === undefined) {
  30473. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30474. }
  30475. }
  30476. }
  30477. if (!flat) {
  30478. for (i = 0; i < data.vertex.length; i++) {
  30479. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30480. uvs.push(0, 0);
  30481. }
  30482. for (f = 0; f < nbfaces; f++) {
  30483. for (i = 0; i < data.face[f].length - 2; i++) {
  30484. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30485. }
  30486. }
  30487. }
  30488. else {
  30489. for (f = 0; f < nbfaces; f++) {
  30490. var fl = data.face[f].length; // number of vertices of the current face
  30491. ang = 2 * Math.PI / fl;
  30492. x = 0.5 * Math.tan(ang / 2);
  30493. y = 0.5;
  30494. // positions, uvs, colors
  30495. for (i = 0; i < fl; i++) {
  30496. // positions
  30497. 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);
  30498. indexes.push(index);
  30499. index++;
  30500. // uvs
  30501. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30502. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30503. uvs.push(u, v);
  30504. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30505. y = x * Math.sin(ang) + y * Math.cos(ang);
  30506. x = tmp;
  30507. // colors
  30508. if (faceColors) {
  30509. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30510. }
  30511. }
  30512. // indices from indexes
  30513. for (i = 0; i < fl - 2; i++) {
  30514. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30515. }
  30516. faceIdx += fl;
  30517. }
  30518. }
  30519. VertexData.ComputeNormals(positions, indices, normals);
  30520. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30521. var vertexData = new VertexData();
  30522. vertexData.positions = positions;
  30523. vertexData.indices = indices;
  30524. vertexData.normals = normals;
  30525. vertexData.uvs = uvs;
  30526. if (faceColors && flat) {
  30527. vertexData.colors = colors;
  30528. }
  30529. return vertexData;
  30530. };
  30531. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30532. /**
  30533. * Creates the VertexData of the Torus Knot.
  30534. */
  30535. VertexData.CreateTorusKnot = function (options) {
  30536. var indices = new Array();
  30537. var positions = new Array();
  30538. var normals = new Array();
  30539. var uvs = new Array();
  30540. var radius = options.radius || 2;
  30541. var tube = options.tube || 0.5;
  30542. var radialSegments = options.radialSegments || 32;
  30543. var tubularSegments = options.tubularSegments || 32;
  30544. var p = options.p || 2;
  30545. var q = options.q || 3;
  30546. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30547. // Helper
  30548. var getPos = function (angle) {
  30549. var cu = Math.cos(angle);
  30550. var su = Math.sin(angle);
  30551. var quOverP = q / p * angle;
  30552. var cs = Math.cos(quOverP);
  30553. var tx = radius * (2 + cs) * 0.5 * cu;
  30554. var ty = radius * (2 + cs) * su * 0.5;
  30555. var tz = radius * Math.sin(quOverP) * 0.5;
  30556. return new BABYLON.Vector3(tx, ty, tz);
  30557. };
  30558. // Vertices
  30559. var i;
  30560. var j;
  30561. for (i = 0; i <= radialSegments; i++) {
  30562. var modI = i % radialSegments;
  30563. var u = modI / radialSegments * 2 * p * Math.PI;
  30564. var p1 = getPos(u);
  30565. var p2 = getPos(u + 0.01);
  30566. var tang = p2.subtract(p1);
  30567. var n = p2.add(p1);
  30568. var bitan = BABYLON.Vector3.Cross(tang, n);
  30569. n = BABYLON.Vector3.Cross(bitan, tang);
  30570. bitan.normalize();
  30571. n.normalize();
  30572. for (j = 0; j < tubularSegments; j++) {
  30573. var modJ = j % tubularSegments;
  30574. var v = modJ / tubularSegments * 2 * Math.PI;
  30575. var cx = -tube * Math.cos(v);
  30576. var cy = tube * Math.sin(v);
  30577. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30578. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30579. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30580. uvs.push(i / radialSegments);
  30581. uvs.push(j / tubularSegments);
  30582. }
  30583. }
  30584. for (i = 0; i < radialSegments; i++) {
  30585. for (j = 0; j < tubularSegments; j++) {
  30586. var jNext = (j + 1) % tubularSegments;
  30587. var a = i * tubularSegments + j;
  30588. var b = (i + 1) * tubularSegments + j;
  30589. var c = (i + 1) * tubularSegments + jNext;
  30590. var d = i * tubularSegments + jNext;
  30591. indices.push(d);
  30592. indices.push(b);
  30593. indices.push(a);
  30594. indices.push(d);
  30595. indices.push(c);
  30596. indices.push(b);
  30597. }
  30598. }
  30599. // Normals
  30600. VertexData.ComputeNormals(positions, indices, normals);
  30601. // Sides
  30602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30603. // Result
  30604. var vertexData = new VertexData();
  30605. vertexData.indices = indices;
  30606. vertexData.positions = positions;
  30607. vertexData.normals = normals;
  30608. vertexData.uvs = uvs;
  30609. return vertexData;
  30610. };
  30611. // Tools
  30612. /**
  30613. * @param {any} - positions (number[] or Float32Array)
  30614. * @param {any} - indices (number[] or Uint16Array)
  30615. * @param {any} - normals (number[] or Float32Array)
  30616. * options (optional) :
  30617. * facetPositions : optional array of facet positions (vector3)
  30618. * facetNormals : optional array of facet normals (vector3)
  30619. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30620. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30621. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30622. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30623. * bInfo : optional bounding info, required for facetPartitioning computation
  30624. * useRightHandedSystem: optional boolean to for right handed system computation
  30625. * depthSort : optional boolean to enable the facet depth sort computation
  30626. * distanceTo : optional Vector3 to compute the facet depth from this location
  30627. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30628. */
  30629. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30630. // temporary scalar variables
  30631. var index = 0; // facet index
  30632. var p1p2x = 0.0; // p1p2 vector x coordinate
  30633. var p1p2y = 0.0; // p1p2 vector y coordinate
  30634. var p1p2z = 0.0; // p1p2 vector z coordinate
  30635. var p3p2x = 0.0; // p3p2 vector x coordinate
  30636. var p3p2y = 0.0; // p3p2 vector y coordinate
  30637. var p3p2z = 0.0; // p3p2 vector z coordinate
  30638. var faceNormalx = 0.0; // facet normal x coordinate
  30639. var faceNormaly = 0.0; // facet normal y coordinate
  30640. var faceNormalz = 0.0; // facet normal z coordinate
  30641. var length = 0.0; // facet normal length before normalization
  30642. var v1x = 0; // vector1 x index in the positions array
  30643. var v1y = 0; // vector1 y index in the positions array
  30644. var v1z = 0; // vector1 z index in the positions array
  30645. var v2x = 0; // vector2 x index in the positions array
  30646. var v2y = 0; // vector2 y index in the positions array
  30647. var v2z = 0; // vector2 z index in the positions array
  30648. var v3x = 0; // vector3 x index in the positions array
  30649. var v3y = 0; // vector3 y index in the positions array
  30650. var v3z = 0; // vector3 z index in the positions array
  30651. var computeFacetNormals = false;
  30652. var computeFacetPositions = false;
  30653. var computeFacetPartitioning = false;
  30654. var computeDepthSort = false;
  30655. var faceNormalSign = 1;
  30656. var ratio = 0;
  30657. var distanceTo = null;
  30658. if (options) {
  30659. computeFacetNormals = (options.facetNormals) ? true : false;
  30660. computeFacetPositions = (options.facetPositions) ? true : false;
  30661. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30662. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30663. ratio = options.ratio || 0;
  30664. computeDepthSort = (options.depthSort) ? true : false;
  30665. distanceTo = (options.distanceTo);
  30666. if (computeDepthSort) {
  30667. if (distanceTo === undefined) {
  30668. distanceTo = BABYLON.Vector3.Zero();
  30669. }
  30670. var depthSortedFacets = options.depthSortedFacets;
  30671. }
  30672. }
  30673. // facetPartitioning reinit if needed
  30674. var xSubRatio = 0;
  30675. var ySubRatio = 0;
  30676. var zSubRatio = 0;
  30677. var subSq = 0;
  30678. if (computeFacetPartitioning && options && options.bbSize) {
  30679. var ox = 0; // X partitioning index for facet position
  30680. var oy = 0; // Y partinioning index for facet position
  30681. var oz = 0; // Z partinioning index for facet position
  30682. var b1x = 0; // X partitioning index for facet v1 vertex
  30683. var b1y = 0; // Y partitioning index for facet v1 vertex
  30684. var b1z = 0; // z partitioning index for facet v1 vertex
  30685. var b2x = 0; // X partitioning index for facet v2 vertex
  30686. var b2y = 0; // Y partitioning index for facet v2 vertex
  30687. var b2z = 0; // Z partitioning index for facet v2 vertex
  30688. var b3x = 0; // X partitioning index for facet v3 vertex
  30689. var b3y = 0; // Y partitioning index for facet v3 vertex
  30690. var b3z = 0; // Z partitioning index for facet v3 vertex
  30691. var block_idx_o = 0; // facet barycenter block index
  30692. var block_idx_v1 = 0; // v1 vertex block index
  30693. var block_idx_v2 = 0; // v2 vertex block index
  30694. var block_idx_v3 = 0; // v3 vertex block index
  30695. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30696. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30697. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30698. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30699. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30700. subSq = options.subDiv.max * options.subDiv.max;
  30701. options.facetPartitioning.length = 0;
  30702. }
  30703. // reset the normals
  30704. for (index = 0; index < positions.length; index++) {
  30705. normals[index] = 0.0;
  30706. }
  30707. // Loop : 1 indice triplet = 1 facet
  30708. var nbFaces = (indices.length / 3) | 0;
  30709. for (index = 0; index < nbFaces; index++) {
  30710. // get the indexes of the coordinates of each vertex of the facet
  30711. v1x = indices[index * 3] * 3;
  30712. v1y = v1x + 1;
  30713. v1z = v1x + 2;
  30714. v2x = indices[index * 3 + 1] * 3;
  30715. v2y = v2x + 1;
  30716. v2z = v2x + 2;
  30717. v3x = indices[index * 3 + 2] * 3;
  30718. v3y = v3x + 1;
  30719. v3z = v3x + 2;
  30720. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30721. p1p2y = positions[v1y] - positions[v2y];
  30722. p1p2z = positions[v1z] - positions[v2z];
  30723. p3p2x = positions[v3x] - positions[v2x];
  30724. p3p2y = positions[v3y] - positions[v2y];
  30725. p3p2z = positions[v3z] - positions[v2z];
  30726. // compute the face normal with the cross product
  30727. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30728. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30729. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30730. // normalize this normal and store it in the array facetData
  30731. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30732. length = (length === 0) ? 1.0 : length;
  30733. faceNormalx /= length;
  30734. faceNormaly /= length;
  30735. faceNormalz /= length;
  30736. if (computeFacetNormals && options) {
  30737. options.facetNormals[index].x = faceNormalx;
  30738. options.facetNormals[index].y = faceNormaly;
  30739. options.facetNormals[index].z = faceNormalz;
  30740. }
  30741. if (computeFacetPositions && options) {
  30742. // compute and the facet barycenter coordinates in the array facetPositions
  30743. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30744. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30745. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30746. }
  30747. if (computeFacetPartitioning && options) {
  30748. // store the facet indexes in arrays in the main facetPartitioning array :
  30749. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30750. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30751. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30752. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30753. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30754. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30755. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30756. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30757. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30758. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30759. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30760. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30761. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30762. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30763. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30764. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30765. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30766. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30767. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30768. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30769. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30770. // push each facet index in each block containing the vertex
  30771. options.facetPartitioning[block_idx_v1].push(index);
  30772. if (block_idx_v2 != block_idx_v1) {
  30773. options.facetPartitioning[block_idx_v2].push(index);
  30774. }
  30775. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30776. options.facetPartitioning[block_idx_v3].push(index);
  30777. }
  30778. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30779. options.facetPartitioning[block_idx_o].push(index);
  30780. }
  30781. }
  30782. if (computeDepthSort && options && options.facetPositions) {
  30783. var dsf = depthSortedFacets[index];
  30784. dsf.ind = index * 3;
  30785. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30786. }
  30787. // compute the normals anyway
  30788. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30789. normals[v1y] += faceNormaly;
  30790. normals[v1z] += faceNormalz;
  30791. normals[v2x] += faceNormalx;
  30792. normals[v2y] += faceNormaly;
  30793. normals[v2z] += faceNormalz;
  30794. normals[v3x] += faceNormalx;
  30795. normals[v3y] += faceNormaly;
  30796. normals[v3z] += faceNormalz;
  30797. }
  30798. // last normalization of each normal
  30799. for (index = 0; index < normals.length / 3; index++) {
  30800. faceNormalx = normals[index * 3];
  30801. faceNormaly = normals[index * 3 + 1];
  30802. faceNormalz = normals[index * 3 + 2];
  30803. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30804. length = (length === 0) ? 1.0 : length;
  30805. faceNormalx /= length;
  30806. faceNormaly /= length;
  30807. faceNormalz /= length;
  30808. normals[index * 3] = faceNormalx;
  30809. normals[index * 3 + 1] = faceNormaly;
  30810. normals[index * 3 + 2] = faceNormalz;
  30811. }
  30812. };
  30813. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30814. var li = indices.length;
  30815. var ln = normals.length;
  30816. var i;
  30817. var n;
  30818. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30819. switch (sideOrientation) {
  30820. case BABYLON.Mesh.FRONTSIDE:
  30821. // nothing changed
  30822. break;
  30823. case BABYLON.Mesh.BACKSIDE:
  30824. var tmp;
  30825. // indices
  30826. for (i = 0; i < li; i += 3) {
  30827. tmp = indices[i];
  30828. indices[i] = indices[i + 2];
  30829. indices[i + 2] = tmp;
  30830. }
  30831. // normals
  30832. for (n = 0; n < ln; n++) {
  30833. normals[n] = -normals[n];
  30834. }
  30835. break;
  30836. case BABYLON.Mesh.DOUBLESIDE:
  30837. // positions
  30838. var lp = positions.length;
  30839. var l = lp / 3;
  30840. for (var p = 0; p < lp; p++) {
  30841. positions[lp + p] = positions[p];
  30842. }
  30843. // indices
  30844. for (i = 0; i < li; i += 3) {
  30845. indices[i + li] = indices[i + 2] + l;
  30846. indices[i + 1 + li] = indices[i + 1] + l;
  30847. indices[i + 2 + li] = indices[i] + l;
  30848. }
  30849. // normals
  30850. for (n = 0; n < ln; n++) {
  30851. normals[ln + n] = -normals[n];
  30852. }
  30853. // uvs
  30854. var lu = uvs.length;
  30855. var u = 0;
  30856. for (u = 0; u < lu; u++) {
  30857. uvs[u + lu] = uvs[u];
  30858. }
  30859. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30860. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30861. u = 0;
  30862. for (i = 0; i < lu / 2; i++) {
  30863. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30864. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30865. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30866. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30867. u += 2;
  30868. }
  30869. break;
  30870. }
  30871. };
  30872. /**
  30873. * Creates a new VertexData from the imported parameters.
  30874. */
  30875. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30876. var vertexData = new VertexData();
  30877. // positions
  30878. var positions = parsedVertexData.positions;
  30879. if (positions) {
  30880. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30881. }
  30882. // normals
  30883. var normals = parsedVertexData.normals;
  30884. if (normals) {
  30885. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30886. }
  30887. // tangents
  30888. var tangents = parsedVertexData.tangents;
  30889. if (tangents) {
  30890. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30891. }
  30892. // uvs
  30893. var uvs = parsedVertexData.uvs;
  30894. if (uvs) {
  30895. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30896. }
  30897. // uv2s
  30898. var uv2s = parsedVertexData.uv2s;
  30899. if (uv2s) {
  30900. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30901. }
  30902. // uv3s
  30903. var uv3s = parsedVertexData.uv3s;
  30904. if (uv3s) {
  30905. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30906. }
  30907. // uv4s
  30908. var uv4s = parsedVertexData.uv4s;
  30909. if (uv4s) {
  30910. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30911. }
  30912. // uv5s
  30913. var uv5s = parsedVertexData.uv5s;
  30914. if (uv5s) {
  30915. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30916. }
  30917. // uv6s
  30918. var uv6s = parsedVertexData.uv6s;
  30919. if (uv6s) {
  30920. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30921. }
  30922. // colors
  30923. var colors = parsedVertexData.colors;
  30924. if (colors) {
  30925. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30926. }
  30927. // matricesIndices
  30928. var matricesIndices = parsedVertexData.matricesIndices;
  30929. if (matricesIndices) {
  30930. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30931. }
  30932. // matricesWeights
  30933. var matricesWeights = parsedVertexData.matricesWeights;
  30934. if (matricesWeights) {
  30935. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30936. }
  30937. // indices
  30938. var indices = parsedVertexData.indices;
  30939. if (indices) {
  30940. vertexData.indices = indices;
  30941. }
  30942. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30943. };
  30944. return VertexData;
  30945. }());
  30946. BABYLON.VertexData = VertexData;
  30947. })(BABYLON || (BABYLON = {}));
  30948. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30949. var BABYLON;
  30950. (function (BABYLON) {
  30951. var Geometry = /** @class */ (function () {
  30952. function Geometry(id, scene, vertexData, updatable, mesh) {
  30953. if (updatable === void 0) { updatable = false; }
  30954. if (mesh === void 0) { mesh = null; }
  30955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30956. this._totalVertices = 0;
  30957. this._isDisposed = false;
  30958. this._indexBufferIsUpdatable = false;
  30959. this.id = id;
  30960. this._engine = scene.getEngine();
  30961. this._meshes = [];
  30962. this._scene = scene;
  30963. //Init vertex buffer cache
  30964. this._vertexBuffers = {};
  30965. this._indices = [];
  30966. this._updatable = updatable;
  30967. // vertexData
  30968. if (vertexData) {
  30969. this.setAllVerticesData(vertexData, updatable);
  30970. }
  30971. else {
  30972. this._totalVertices = 0;
  30973. this._indices = [];
  30974. }
  30975. if (this._engine.getCaps().vertexArrayObject) {
  30976. this._vertexArrayObjects = {};
  30977. }
  30978. // applyToMesh
  30979. if (mesh) {
  30980. if (mesh.getClassName() === "LinesMesh") {
  30981. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30982. this.updateExtend();
  30983. }
  30984. this.applyToMesh(mesh);
  30985. mesh.computeWorldMatrix(true);
  30986. }
  30987. }
  30988. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30989. /**
  30990. * 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
  30991. * @returns The Bias Vector
  30992. */
  30993. get: function () {
  30994. return this._boundingBias;
  30995. },
  30996. set: function (value) {
  30997. if (this._boundingBias && this._boundingBias.equals(value)) {
  30998. return;
  30999. }
  31000. this._boundingBias = value.clone();
  31001. this.updateBoundingInfo(true, null);
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Geometry.CreateGeometryForMesh = function (mesh) {
  31007. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31008. geometry.applyToMesh(mesh);
  31009. return geometry;
  31010. };
  31011. Object.defineProperty(Geometry.prototype, "extend", {
  31012. get: function () {
  31013. return this._extend;
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. Geometry.prototype.getScene = function () {
  31019. return this._scene;
  31020. };
  31021. Geometry.prototype.getEngine = function () {
  31022. return this._engine;
  31023. };
  31024. Geometry.prototype.isReady = function () {
  31025. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31026. };
  31027. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31028. get: function () {
  31029. for (var index = 0; index < this._meshes.length; index++) {
  31030. if (!this._meshes[index].doNotSerialize) {
  31031. return false;
  31032. }
  31033. }
  31034. return true;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. Geometry.prototype._rebuild = function () {
  31040. if (this._vertexArrayObjects) {
  31041. this._vertexArrayObjects = {};
  31042. }
  31043. // Index buffer
  31044. if (this._meshes.length !== 0 && this._indices) {
  31045. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31046. }
  31047. // Vertex buffers
  31048. for (var key in this._vertexBuffers) {
  31049. var vertexBuffer = this._vertexBuffers[key];
  31050. vertexBuffer._rebuild();
  31051. }
  31052. };
  31053. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31054. vertexData.applyToGeometry(this, updatable);
  31055. this.notifyUpdate();
  31056. };
  31057. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31058. if (updatable === void 0) { updatable = false; }
  31059. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31060. this.setVerticesBuffer(buffer);
  31061. };
  31062. Geometry.prototype.removeVerticesData = function (kind) {
  31063. if (this._vertexBuffers[kind]) {
  31064. this._vertexBuffers[kind].dispose();
  31065. delete this._vertexBuffers[kind];
  31066. }
  31067. };
  31068. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31069. var kind = buffer.getKind();
  31070. if (this._vertexBuffers[kind]) {
  31071. this._vertexBuffers[kind].dispose();
  31072. }
  31073. this._vertexBuffers[kind] = buffer;
  31074. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31075. var data = buffer.getData();
  31076. var stride = buffer.getStrideSize();
  31077. this._totalVertices = data.length / stride;
  31078. this.updateExtend(data, stride);
  31079. this._resetPointsArrayCache();
  31080. var meshes = this._meshes;
  31081. var numOfMeshes = meshes.length;
  31082. for (var index = 0; index < numOfMeshes; index++) {
  31083. var mesh = meshes[index];
  31084. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31085. mesh._createGlobalSubMesh(false);
  31086. mesh.computeWorldMatrix(true);
  31087. }
  31088. }
  31089. this.notifyUpdate(kind);
  31090. if (this._vertexArrayObjects) {
  31091. this._disposeVertexArrayObjects();
  31092. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31093. }
  31094. };
  31095. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31096. var vertexBuffer = this.getVertexBuffer(kind);
  31097. if (!vertexBuffer) {
  31098. return;
  31099. }
  31100. vertexBuffer.updateDirectly(data, offset);
  31101. this.notifyUpdate(kind);
  31102. };
  31103. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31104. if (updateExtends === void 0) { updateExtends = false; }
  31105. var vertexBuffer = this.getVertexBuffer(kind);
  31106. if (!vertexBuffer) {
  31107. return;
  31108. }
  31109. vertexBuffer.update(data);
  31110. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31111. var stride = vertexBuffer.getStrideSize();
  31112. this._totalVertices = data.length / stride;
  31113. this.updateBoundingInfo(updateExtends, data);
  31114. }
  31115. this.notifyUpdate(kind);
  31116. };
  31117. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31118. if (updateExtends) {
  31119. this.updateExtend(data);
  31120. }
  31121. var meshes = this._meshes;
  31122. var numOfMeshes = meshes.length;
  31123. this._resetPointsArrayCache();
  31124. for (var index = 0; index < numOfMeshes; index++) {
  31125. var mesh = meshes[index];
  31126. if (updateExtends) {
  31127. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31128. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31129. var subMesh = mesh.subMeshes[subIndex];
  31130. subMesh.refreshBoundingInfo();
  31131. }
  31132. }
  31133. }
  31134. };
  31135. Geometry.prototype._bind = function (effect, indexToBind) {
  31136. if (!effect) {
  31137. return;
  31138. }
  31139. if (indexToBind === undefined) {
  31140. indexToBind = this._indexBuffer;
  31141. }
  31142. var vbs = this.getVertexBuffers();
  31143. if (!vbs) {
  31144. return;
  31145. }
  31146. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31147. this._engine.bindBuffers(vbs, indexToBind, effect);
  31148. return;
  31149. }
  31150. // Using VAO
  31151. if (!this._vertexArrayObjects[effect.key]) {
  31152. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31153. }
  31154. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31155. };
  31156. Geometry.prototype.getTotalVertices = function () {
  31157. if (!this.isReady()) {
  31158. return 0;
  31159. }
  31160. return this._totalVertices;
  31161. };
  31162. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31163. var vertexBuffer = this.getVertexBuffer(kind);
  31164. if (!vertexBuffer) {
  31165. return null;
  31166. }
  31167. var orig = vertexBuffer.getData();
  31168. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31169. return orig;
  31170. }
  31171. else {
  31172. var len = orig.length;
  31173. var copy = [];
  31174. for (var i = 0; i < len; i++) {
  31175. copy.push(orig[i]);
  31176. }
  31177. return copy;
  31178. }
  31179. };
  31180. /**
  31181. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31182. * Possible `kind` values :
  31183. * - BABYLON.VertexBuffer.PositionKind
  31184. * - BABYLON.VertexBuffer.UVKind
  31185. * - BABYLON.VertexBuffer.UV2Kind
  31186. * - BABYLON.VertexBuffer.UV3Kind
  31187. * - BABYLON.VertexBuffer.UV4Kind
  31188. * - BABYLON.VertexBuffer.UV5Kind
  31189. * - BABYLON.VertexBuffer.UV6Kind
  31190. * - BABYLON.VertexBuffer.ColorKind
  31191. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31192. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31193. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31194. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31195. */
  31196. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31197. var vb = this._vertexBuffers[kind];
  31198. if (!vb) {
  31199. return false;
  31200. }
  31201. return vb.isUpdatable();
  31202. };
  31203. Geometry.prototype.getVertexBuffer = function (kind) {
  31204. if (!this.isReady()) {
  31205. return null;
  31206. }
  31207. return this._vertexBuffers[kind];
  31208. };
  31209. Geometry.prototype.getVertexBuffers = function () {
  31210. if (!this.isReady()) {
  31211. return null;
  31212. }
  31213. return this._vertexBuffers;
  31214. };
  31215. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31216. if (!this._vertexBuffers) {
  31217. if (this._delayInfo) {
  31218. return this._delayInfo.indexOf(kind) !== -1;
  31219. }
  31220. return false;
  31221. }
  31222. return this._vertexBuffers[kind] !== undefined;
  31223. };
  31224. Geometry.prototype.getVerticesDataKinds = function () {
  31225. var result = [];
  31226. var kind;
  31227. if (!this._vertexBuffers && this._delayInfo) {
  31228. for (kind in this._delayInfo) {
  31229. result.push(kind);
  31230. }
  31231. }
  31232. else {
  31233. for (kind in this._vertexBuffers) {
  31234. result.push(kind);
  31235. }
  31236. }
  31237. return result;
  31238. };
  31239. Geometry.prototype.updateIndices = function (indices, offset) {
  31240. if (!this._indexBuffer) {
  31241. return;
  31242. }
  31243. if (!this._indexBufferIsUpdatable) {
  31244. this.setIndices(indices, null, true);
  31245. }
  31246. else {
  31247. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31248. }
  31249. };
  31250. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31251. if (totalVertices === void 0) { totalVertices = null; }
  31252. if (updatable === void 0) { updatable = false; }
  31253. if (this._indexBuffer) {
  31254. this._engine._releaseBuffer(this._indexBuffer);
  31255. }
  31256. this._disposeVertexArrayObjects();
  31257. this._indices = indices;
  31258. this._indexBufferIsUpdatable = updatable;
  31259. if (this._meshes.length !== 0 && this._indices) {
  31260. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31261. }
  31262. if (totalVertices != undefined) {
  31263. this._totalVertices = totalVertices;
  31264. }
  31265. var meshes = this._meshes;
  31266. var numOfMeshes = meshes.length;
  31267. for (var index = 0; index < numOfMeshes; index++) {
  31268. meshes[index]._createGlobalSubMesh(true);
  31269. }
  31270. this.notifyUpdate();
  31271. };
  31272. Geometry.prototype.getTotalIndices = function () {
  31273. if (!this.isReady()) {
  31274. return 0;
  31275. }
  31276. return this._indices.length;
  31277. };
  31278. Geometry.prototype.getIndices = function (copyWhenShared) {
  31279. if (!this.isReady()) {
  31280. return null;
  31281. }
  31282. var orig = this._indices;
  31283. if (!copyWhenShared || this._meshes.length === 1) {
  31284. return orig;
  31285. }
  31286. else {
  31287. var len = orig.length;
  31288. var copy = [];
  31289. for (var i = 0; i < len; i++) {
  31290. copy.push(orig[i]);
  31291. }
  31292. return copy;
  31293. }
  31294. };
  31295. Geometry.prototype.getIndexBuffer = function () {
  31296. if (!this.isReady()) {
  31297. return null;
  31298. }
  31299. return this._indexBuffer;
  31300. };
  31301. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31302. if (effect === void 0) { effect = null; }
  31303. if (!effect || !this._vertexArrayObjects) {
  31304. return;
  31305. }
  31306. if (this._vertexArrayObjects[effect.key]) {
  31307. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31308. delete this._vertexArrayObjects[effect.key];
  31309. }
  31310. };
  31311. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31312. var meshes = this._meshes;
  31313. var index = meshes.indexOf(mesh);
  31314. if (index === -1) {
  31315. return;
  31316. }
  31317. meshes.splice(index, 1);
  31318. mesh._geometry = null;
  31319. if (meshes.length === 0 && shouldDispose) {
  31320. this.dispose();
  31321. }
  31322. };
  31323. Geometry.prototype.applyToMesh = function (mesh) {
  31324. if (mesh._geometry === this) {
  31325. return;
  31326. }
  31327. var previousGeometry = mesh._geometry;
  31328. if (previousGeometry) {
  31329. previousGeometry.releaseForMesh(mesh);
  31330. }
  31331. var meshes = this._meshes;
  31332. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31333. mesh._geometry = this;
  31334. this._scene.pushGeometry(this);
  31335. meshes.push(mesh);
  31336. if (this.isReady()) {
  31337. this._applyToMesh(mesh);
  31338. }
  31339. else {
  31340. mesh._boundingInfo = this._boundingInfo;
  31341. }
  31342. };
  31343. Geometry.prototype.updateExtend = function (data, stride) {
  31344. if (data === void 0) { data = null; }
  31345. if (!data) {
  31346. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31347. }
  31348. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31349. };
  31350. Geometry.prototype._applyToMesh = function (mesh) {
  31351. var numOfMeshes = this._meshes.length;
  31352. // vertexBuffers
  31353. for (var kind in this._vertexBuffers) {
  31354. if (numOfMeshes === 1) {
  31355. this._vertexBuffers[kind].create();
  31356. }
  31357. var buffer = this._vertexBuffers[kind].getBuffer();
  31358. if (buffer)
  31359. buffer.references = numOfMeshes;
  31360. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31361. if (!this._extend) {
  31362. this.updateExtend(this._vertexBuffers[kind].getData());
  31363. }
  31364. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31365. mesh._createGlobalSubMesh(false);
  31366. //bounding info was just created again, world matrix should be applied again.
  31367. mesh._updateBoundingInfo();
  31368. }
  31369. }
  31370. // indexBuffer
  31371. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31372. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31373. }
  31374. if (this._indexBuffer) {
  31375. this._indexBuffer.references = numOfMeshes;
  31376. }
  31377. };
  31378. Geometry.prototype.notifyUpdate = function (kind) {
  31379. if (this.onGeometryUpdated) {
  31380. this.onGeometryUpdated(this, kind);
  31381. }
  31382. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31383. var mesh = _a[_i];
  31384. mesh._markSubMeshesAsAttributesDirty();
  31385. }
  31386. };
  31387. Geometry.prototype.load = function (scene, onLoaded) {
  31388. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31389. return;
  31390. }
  31391. if (this.isReady()) {
  31392. if (onLoaded) {
  31393. onLoaded();
  31394. }
  31395. return;
  31396. }
  31397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31398. this._queueLoad(scene, onLoaded);
  31399. };
  31400. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31401. var _this = this;
  31402. if (!this.delayLoadingFile) {
  31403. return;
  31404. }
  31405. scene._addPendingData(this);
  31406. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31407. if (!_this._delayLoadingFunction) {
  31408. return;
  31409. }
  31410. _this._delayLoadingFunction(JSON.parse(data), _this);
  31411. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31412. _this._delayInfo = [];
  31413. scene._removePendingData(_this);
  31414. var meshes = _this._meshes;
  31415. var numOfMeshes = meshes.length;
  31416. for (var index = 0; index < numOfMeshes; index++) {
  31417. _this._applyToMesh(meshes[index]);
  31418. }
  31419. if (onLoaded) {
  31420. onLoaded();
  31421. }
  31422. }, function () { }, scene.database);
  31423. };
  31424. /**
  31425. * Invert the geometry to move from a right handed system to a left handed one.
  31426. */
  31427. Geometry.prototype.toLeftHanded = function () {
  31428. // Flip faces
  31429. var tIndices = this.getIndices(false);
  31430. if (tIndices != null && tIndices.length > 0) {
  31431. for (var i = 0; i < tIndices.length; i += 3) {
  31432. var tTemp = tIndices[i + 0];
  31433. tIndices[i + 0] = tIndices[i + 2];
  31434. tIndices[i + 2] = tTemp;
  31435. }
  31436. this.setIndices(tIndices);
  31437. }
  31438. // Negate position.z
  31439. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31440. if (tPositions != null && tPositions.length > 0) {
  31441. for (var i = 0; i < tPositions.length; i += 3) {
  31442. tPositions[i + 2] = -tPositions[i + 2];
  31443. }
  31444. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31445. }
  31446. // Negate normal.z
  31447. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31448. if (tNormals != null && tNormals.length > 0) {
  31449. for (var i = 0; i < tNormals.length; i += 3) {
  31450. tNormals[i + 2] = -tNormals[i + 2];
  31451. }
  31452. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31453. }
  31454. };
  31455. // Cache
  31456. Geometry.prototype._resetPointsArrayCache = function () {
  31457. this._positions = null;
  31458. };
  31459. Geometry.prototype._generatePointsArray = function () {
  31460. if (this._positions)
  31461. return true;
  31462. this._positions = [];
  31463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31464. if (!data) {
  31465. return false;
  31466. }
  31467. for (var index = 0; index < data.length; index += 3) {
  31468. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31469. }
  31470. return true;
  31471. };
  31472. Geometry.prototype.isDisposed = function () {
  31473. return this._isDisposed;
  31474. };
  31475. Geometry.prototype._disposeVertexArrayObjects = function () {
  31476. if (this._vertexArrayObjects) {
  31477. for (var kind in this._vertexArrayObjects) {
  31478. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31479. }
  31480. this._vertexArrayObjects = {};
  31481. }
  31482. };
  31483. Geometry.prototype.dispose = function () {
  31484. var meshes = this._meshes;
  31485. var numOfMeshes = meshes.length;
  31486. var index;
  31487. for (index = 0; index < numOfMeshes; index++) {
  31488. this.releaseForMesh(meshes[index]);
  31489. }
  31490. this._meshes = [];
  31491. this._disposeVertexArrayObjects();
  31492. for (var kind in this._vertexBuffers) {
  31493. this._vertexBuffers[kind].dispose();
  31494. }
  31495. this._vertexBuffers = {};
  31496. this._totalVertices = 0;
  31497. if (this._indexBuffer) {
  31498. this._engine._releaseBuffer(this._indexBuffer);
  31499. }
  31500. this._indexBuffer = null;
  31501. this._indices = [];
  31502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31503. this.delayLoadingFile = null;
  31504. this._delayLoadingFunction = null;
  31505. this._delayInfo = [];
  31506. this._boundingInfo = null;
  31507. this._scene.removeGeometry(this);
  31508. this._isDisposed = true;
  31509. };
  31510. Geometry.prototype.copy = function (id) {
  31511. var vertexData = new BABYLON.VertexData();
  31512. vertexData.indices = [];
  31513. var indices = this.getIndices();
  31514. if (indices) {
  31515. for (var index = 0; index < indices.length; index++) {
  31516. vertexData.indices.push(indices[index]);
  31517. }
  31518. }
  31519. var updatable = false;
  31520. var stopChecking = false;
  31521. var kind;
  31522. for (kind in this._vertexBuffers) {
  31523. // using slice() to make a copy of the array and not just reference it
  31524. var data = this.getVerticesData(kind);
  31525. if (data instanceof Float32Array) {
  31526. vertexData.set(new Float32Array(data), kind);
  31527. }
  31528. else {
  31529. vertexData.set(data.slice(0), kind);
  31530. }
  31531. if (!stopChecking) {
  31532. var vb = this.getVertexBuffer(kind);
  31533. if (vb) {
  31534. updatable = vb.isUpdatable();
  31535. stopChecking = !updatable;
  31536. }
  31537. }
  31538. }
  31539. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31540. geometry.delayLoadState = this.delayLoadState;
  31541. geometry.delayLoadingFile = this.delayLoadingFile;
  31542. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31543. for (kind in this._delayInfo) {
  31544. geometry._delayInfo = geometry._delayInfo || [];
  31545. geometry._delayInfo.push(kind);
  31546. }
  31547. // Bounding info
  31548. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31549. return geometry;
  31550. };
  31551. Geometry.prototype.serialize = function () {
  31552. var serializationObject = {};
  31553. serializationObject.id = this.id;
  31554. serializationObject.updatable = this._updatable;
  31555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31557. }
  31558. return serializationObject;
  31559. };
  31560. Geometry.prototype.toNumberArray = function (origin) {
  31561. if (Array.isArray(origin)) {
  31562. return origin;
  31563. }
  31564. else {
  31565. return Array.prototype.slice.call(origin);
  31566. }
  31567. };
  31568. Geometry.prototype.serializeVerticeData = function () {
  31569. var serializationObject = this.serialize();
  31570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31571. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31572. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31573. serializationObject.positions._updatable = true;
  31574. }
  31575. }
  31576. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31577. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31578. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31579. serializationObject.normals._updatable = true;
  31580. }
  31581. }
  31582. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31583. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31584. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31585. serializationObject.uvs._updatable = true;
  31586. }
  31587. }
  31588. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31589. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31590. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31591. serializationObject.uv2s._updatable = true;
  31592. }
  31593. }
  31594. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31595. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31596. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31597. serializationObject.uv3s._updatable = true;
  31598. }
  31599. }
  31600. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31601. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31602. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31603. serializationObject.uv4s._updatable = true;
  31604. }
  31605. }
  31606. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31607. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31608. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31609. serializationObject.uv5s._updatable = true;
  31610. }
  31611. }
  31612. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31613. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31614. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31615. serializationObject.uv6s._updatable = true;
  31616. }
  31617. }
  31618. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31619. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31620. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31621. serializationObject.colors._updatable = true;
  31622. }
  31623. }
  31624. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31625. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31626. serializationObject.matricesIndices._isExpanded = true;
  31627. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31628. serializationObject.matricesIndices._updatable = true;
  31629. }
  31630. }
  31631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31632. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31633. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31634. serializationObject.matricesWeights._updatable = true;
  31635. }
  31636. }
  31637. serializationObject.indices = this.toNumberArray(this.getIndices());
  31638. return serializationObject;
  31639. };
  31640. // Statics
  31641. Geometry.ExtractFromMesh = function (mesh, id) {
  31642. var geometry = mesh._geometry;
  31643. if (!geometry) {
  31644. return null;
  31645. }
  31646. return geometry.copy(id);
  31647. };
  31648. /**
  31649. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31650. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31651. * Be aware Math.random() could cause collisions, but:
  31652. * "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"
  31653. */
  31654. Geometry.RandomId = function () {
  31655. return BABYLON.Tools.RandomId();
  31656. };
  31657. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31658. var scene = mesh.getScene();
  31659. // Geometry
  31660. var geometryId = parsedGeometry.geometryId;
  31661. if (geometryId) {
  31662. var geometry = scene.getGeometryByID(geometryId);
  31663. if (geometry) {
  31664. geometry.applyToMesh(mesh);
  31665. }
  31666. }
  31667. else if (parsedGeometry instanceof ArrayBuffer) {
  31668. var binaryInfo = mesh._binaryInfo;
  31669. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31670. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31671. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31672. }
  31673. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31674. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31675. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31676. }
  31677. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31678. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31679. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31680. }
  31681. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31682. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31683. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31684. }
  31685. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31686. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31687. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31688. }
  31689. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31690. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31691. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31692. }
  31693. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31694. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31695. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31696. }
  31697. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31698. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31699. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31700. }
  31701. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31702. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31703. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31704. }
  31705. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31706. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31708. }
  31709. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31710. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31712. }
  31713. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31714. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31715. mesh.setIndices(indicesData, null);
  31716. }
  31717. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31718. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31719. mesh.subMeshes = [];
  31720. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31721. var materialIndex = subMeshesData[(i * 5) + 0];
  31722. var verticesStart = subMeshesData[(i * 5) + 1];
  31723. var verticesCount = subMeshesData[(i * 5) + 2];
  31724. var indexStart = subMeshesData[(i * 5) + 3];
  31725. var indexCount = subMeshesData[(i * 5) + 4];
  31726. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31727. }
  31728. }
  31729. }
  31730. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31731. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31732. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31733. if (parsedGeometry.uvs) {
  31734. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31735. }
  31736. if (parsedGeometry.uvs2) {
  31737. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31738. }
  31739. if (parsedGeometry.uvs3) {
  31740. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31741. }
  31742. if (parsedGeometry.uvs4) {
  31743. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31744. }
  31745. if (parsedGeometry.uvs5) {
  31746. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31747. }
  31748. if (parsedGeometry.uvs6) {
  31749. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31750. }
  31751. if (parsedGeometry.colors) {
  31752. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31753. }
  31754. if (parsedGeometry.matricesIndices) {
  31755. if (!parsedGeometry.matricesIndices._isExpanded) {
  31756. var floatIndices = [];
  31757. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31758. var matricesIndex = parsedGeometry.matricesIndices[i];
  31759. floatIndices.push(matricesIndex & 0x000000FF);
  31760. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31761. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31762. floatIndices.push(matricesIndex >> 24);
  31763. }
  31764. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31765. }
  31766. else {
  31767. delete parsedGeometry.matricesIndices._isExpanded;
  31768. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31769. }
  31770. }
  31771. if (parsedGeometry.matricesIndicesExtra) {
  31772. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31773. var floatIndices = [];
  31774. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31775. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31776. floatIndices.push(matricesIndex & 0x000000FF);
  31777. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31778. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31779. floatIndices.push(matricesIndex >> 24);
  31780. }
  31781. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31782. }
  31783. else {
  31784. delete parsedGeometry.matricesIndices._isExpanded;
  31785. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31786. }
  31787. }
  31788. if (parsedGeometry.matricesWeights) {
  31789. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31790. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31791. }
  31792. if (parsedGeometry.matricesWeightsExtra) {
  31793. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31794. }
  31795. mesh.setIndices(parsedGeometry.indices, null);
  31796. }
  31797. // SubMeshes
  31798. if (parsedGeometry.subMeshes) {
  31799. mesh.subMeshes = [];
  31800. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31801. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31802. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31803. }
  31804. }
  31805. // Flat shading
  31806. if (mesh._shouldGenerateFlatShading) {
  31807. mesh.convertToFlatShadedMesh();
  31808. delete mesh._shouldGenerateFlatShading;
  31809. }
  31810. // Update
  31811. mesh.computeWorldMatrix(true);
  31812. // Octree
  31813. if (scene['_selectionOctree']) {
  31814. scene['_selectionOctree'].addMesh(mesh);
  31815. }
  31816. };
  31817. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31818. var epsilon = 1e-3;
  31819. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31820. return;
  31821. }
  31822. var noInfluenceBoneIndex = 0.0;
  31823. if (parsedGeometry.skeletonId > -1) {
  31824. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31825. if (!skeleton) {
  31826. return;
  31827. }
  31828. noInfluenceBoneIndex = skeleton.bones.length;
  31829. }
  31830. else {
  31831. return;
  31832. }
  31833. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31834. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31835. var matricesWeights = parsedGeometry.matricesWeights;
  31836. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31837. var influencers = parsedGeometry.numBoneInfluencer;
  31838. var size = matricesWeights.length;
  31839. for (var i = 0; i < size; i += 4) {
  31840. var weight = 0.0;
  31841. var firstZeroWeight = -1;
  31842. for (var j = 0; j < 4; j++) {
  31843. var w = matricesWeights[i + j];
  31844. weight += w;
  31845. if (w < epsilon && firstZeroWeight < 0) {
  31846. firstZeroWeight = j;
  31847. }
  31848. }
  31849. if (matricesWeightsExtra) {
  31850. for (var j = 0; j < 4; j++) {
  31851. var w = matricesWeightsExtra[i + j];
  31852. weight += w;
  31853. if (w < epsilon && firstZeroWeight < 0) {
  31854. firstZeroWeight = j + 4;
  31855. }
  31856. }
  31857. }
  31858. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31859. firstZeroWeight = influencers - 1;
  31860. }
  31861. if (weight > epsilon) {
  31862. var mweight = 1.0 / weight;
  31863. for (var j = 0; j < 4; j++) {
  31864. matricesWeights[i + j] *= mweight;
  31865. }
  31866. if (matricesWeightsExtra) {
  31867. for (var j = 0; j < 4; j++) {
  31868. matricesWeightsExtra[i + j] *= mweight;
  31869. }
  31870. }
  31871. }
  31872. else {
  31873. if (firstZeroWeight >= 4) {
  31874. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31875. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31876. }
  31877. else {
  31878. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31879. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31880. }
  31881. }
  31882. }
  31883. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31884. if (parsedGeometry.matricesWeightsExtra) {
  31885. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31886. }
  31887. };
  31888. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31889. if (scene.getGeometryByID(parsedVertexData.id)) {
  31890. return null; // null since geometry could be something else than a box...
  31891. }
  31892. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31893. if (BABYLON.Tags) {
  31894. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31895. }
  31896. if (parsedVertexData.delayLoadingFile) {
  31897. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31898. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31899. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31900. geometry._delayInfo = [];
  31901. if (parsedVertexData.hasUVs) {
  31902. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31903. }
  31904. if (parsedVertexData.hasUVs2) {
  31905. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31906. }
  31907. if (parsedVertexData.hasUVs3) {
  31908. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31909. }
  31910. if (parsedVertexData.hasUVs4) {
  31911. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31912. }
  31913. if (parsedVertexData.hasUVs5) {
  31914. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31915. }
  31916. if (parsedVertexData.hasUVs6) {
  31917. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31918. }
  31919. if (parsedVertexData.hasColors) {
  31920. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31921. }
  31922. if (parsedVertexData.hasMatricesIndices) {
  31923. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31924. }
  31925. if (parsedVertexData.hasMatricesWeights) {
  31926. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31927. }
  31928. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31929. }
  31930. else {
  31931. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31932. }
  31933. scene.pushGeometry(geometry, true);
  31934. return geometry;
  31935. };
  31936. return Geometry;
  31937. }());
  31938. BABYLON.Geometry = Geometry;
  31939. /////// Primitives //////////////////////////////////////////////
  31940. (function (Geometry) {
  31941. var Primitives;
  31942. (function (Primitives) {
  31943. /// Abstract class
  31944. var _Primitive = /** @class */ (function (_super) {
  31945. __extends(_Primitive, _super);
  31946. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31947. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31948. if (mesh === void 0) { mesh = null; }
  31949. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31950. _this._canBeRegenerated = _canBeRegenerated;
  31951. _this._beingRegenerated = true;
  31952. _this.regenerate();
  31953. _this._beingRegenerated = false;
  31954. return _this;
  31955. }
  31956. _Primitive.prototype.canBeRegenerated = function () {
  31957. return this._canBeRegenerated;
  31958. };
  31959. _Primitive.prototype.regenerate = function () {
  31960. if (!this._canBeRegenerated) {
  31961. return;
  31962. }
  31963. this._beingRegenerated = true;
  31964. this.setAllVerticesData(this._regenerateVertexData(), false);
  31965. this._beingRegenerated = false;
  31966. };
  31967. _Primitive.prototype.asNewGeometry = function (id) {
  31968. return _super.prototype.copy.call(this, id);
  31969. };
  31970. // overrides
  31971. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31972. if (!this._beingRegenerated) {
  31973. return;
  31974. }
  31975. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31976. };
  31977. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31978. if (!this._beingRegenerated) {
  31979. return;
  31980. }
  31981. _super.prototype.setVerticesData.call(this, kind, data, false);
  31982. };
  31983. // to override
  31984. // protected
  31985. _Primitive.prototype._regenerateVertexData = function () {
  31986. throw new Error("Abstract method");
  31987. };
  31988. _Primitive.prototype.copy = function (id) {
  31989. throw new Error("Must be overriden in sub-classes.");
  31990. };
  31991. _Primitive.prototype.serialize = function () {
  31992. var serializationObject = _super.prototype.serialize.call(this);
  31993. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31994. return serializationObject;
  31995. };
  31996. return _Primitive;
  31997. }(Geometry));
  31998. Primitives._Primitive = _Primitive;
  31999. var Ribbon = /** @class */ (function (_super) {
  32000. __extends(Ribbon, _super);
  32001. // Members
  32002. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32005. _this.pathArray = pathArray;
  32006. _this.closeArray = closeArray;
  32007. _this.closePath = closePath;
  32008. _this.offset = offset;
  32009. _this.side = side;
  32010. return _this;
  32011. }
  32012. Ribbon.prototype._regenerateVertexData = function () {
  32013. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32014. };
  32015. Ribbon.prototype.copy = function (id) {
  32016. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32017. };
  32018. return Ribbon;
  32019. }(_Primitive));
  32020. Primitives.Ribbon = Ribbon;
  32021. var Box = /** @class */ (function (_super) {
  32022. __extends(Box, _super);
  32023. // Members
  32024. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32025. if (mesh === void 0) { mesh = null; }
  32026. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32027. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32028. _this.size = size;
  32029. _this.side = side;
  32030. return _this;
  32031. }
  32032. Box.prototype._regenerateVertexData = function () {
  32033. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32034. };
  32035. Box.prototype.copy = function (id) {
  32036. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32037. };
  32038. Box.prototype.serialize = function () {
  32039. var serializationObject = _super.prototype.serialize.call(this);
  32040. serializationObject.size = this.size;
  32041. return serializationObject;
  32042. };
  32043. Box.Parse = function (parsedBox, scene) {
  32044. if (scene.getGeometryByID(parsedBox.id)) {
  32045. return null; // null since geometry could be something else than a box...
  32046. }
  32047. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32048. if (BABYLON.Tags) {
  32049. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32050. }
  32051. scene.pushGeometry(box, true);
  32052. return box;
  32053. };
  32054. return Box;
  32055. }(_Primitive));
  32056. Primitives.Box = Box;
  32057. var Sphere = /** @class */ (function (_super) {
  32058. __extends(Sphere, _super);
  32059. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32060. if (mesh === void 0) { mesh = null; }
  32061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32063. _this.segments = segments;
  32064. _this.diameter = diameter;
  32065. _this.side = side;
  32066. return _this;
  32067. }
  32068. Sphere.prototype._regenerateVertexData = function () {
  32069. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32070. };
  32071. Sphere.prototype.copy = function (id) {
  32072. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32073. };
  32074. Sphere.prototype.serialize = function () {
  32075. var serializationObject = _super.prototype.serialize.call(this);
  32076. serializationObject.segments = this.segments;
  32077. serializationObject.diameter = this.diameter;
  32078. return serializationObject;
  32079. };
  32080. Sphere.Parse = function (parsedSphere, scene) {
  32081. if (scene.getGeometryByID(parsedSphere.id)) {
  32082. return null; // null since geometry could be something else than a sphere...
  32083. }
  32084. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32085. if (BABYLON.Tags) {
  32086. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32087. }
  32088. scene.pushGeometry(sphere, true);
  32089. return sphere;
  32090. };
  32091. return Sphere;
  32092. }(_Primitive));
  32093. Primitives.Sphere = Sphere;
  32094. var Disc = /** @class */ (function (_super) {
  32095. __extends(Disc, _super);
  32096. // Members
  32097. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32098. if (mesh === void 0) { mesh = null; }
  32099. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32100. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32101. _this.radius = radius;
  32102. _this.tessellation = tessellation;
  32103. _this.side = side;
  32104. return _this;
  32105. }
  32106. Disc.prototype._regenerateVertexData = function () {
  32107. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32108. };
  32109. Disc.prototype.copy = function (id) {
  32110. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32111. };
  32112. return Disc;
  32113. }(_Primitive));
  32114. Primitives.Disc = Disc;
  32115. var Cylinder = /** @class */ (function (_super) {
  32116. __extends(Cylinder, _super);
  32117. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32118. if (subdivisions === void 0) { subdivisions = 1; }
  32119. if (mesh === void 0) { mesh = null; }
  32120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32122. _this.height = height;
  32123. _this.diameterTop = diameterTop;
  32124. _this.diameterBottom = diameterBottom;
  32125. _this.tessellation = tessellation;
  32126. _this.subdivisions = subdivisions;
  32127. _this.side = side;
  32128. return _this;
  32129. }
  32130. Cylinder.prototype._regenerateVertexData = function () {
  32131. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32132. };
  32133. Cylinder.prototype.copy = function (id) {
  32134. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32135. };
  32136. Cylinder.prototype.serialize = function () {
  32137. var serializationObject = _super.prototype.serialize.call(this);
  32138. serializationObject.height = this.height;
  32139. serializationObject.diameterTop = this.diameterTop;
  32140. serializationObject.diameterBottom = this.diameterBottom;
  32141. serializationObject.tessellation = this.tessellation;
  32142. return serializationObject;
  32143. };
  32144. Cylinder.Parse = function (parsedCylinder, scene) {
  32145. if (scene.getGeometryByID(parsedCylinder.id)) {
  32146. return null; // null since geometry could be something else than a cylinder...
  32147. }
  32148. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32149. if (BABYLON.Tags) {
  32150. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32151. }
  32152. scene.pushGeometry(cylinder, true);
  32153. return cylinder;
  32154. };
  32155. return Cylinder;
  32156. }(_Primitive));
  32157. Primitives.Cylinder = Cylinder;
  32158. var Torus = /** @class */ (function (_super) {
  32159. __extends(Torus, _super);
  32160. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32161. if (mesh === void 0) { mesh = null; }
  32162. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32163. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32164. _this.diameter = diameter;
  32165. _this.thickness = thickness;
  32166. _this.tessellation = tessellation;
  32167. _this.side = side;
  32168. return _this;
  32169. }
  32170. Torus.prototype._regenerateVertexData = function () {
  32171. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32172. };
  32173. Torus.prototype.copy = function (id) {
  32174. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32175. };
  32176. Torus.prototype.serialize = function () {
  32177. var serializationObject = _super.prototype.serialize.call(this);
  32178. serializationObject.diameter = this.diameter;
  32179. serializationObject.thickness = this.thickness;
  32180. serializationObject.tessellation = this.tessellation;
  32181. return serializationObject;
  32182. };
  32183. Torus.Parse = function (parsedTorus, scene) {
  32184. if (scene.getGeometryByID(parsedTorus.id)) {
  32185. return null; // null since geometry could be something else than a torus...
  32186. }
  32187. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32188. if (BABYLON.Tags) {
  32189. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32190. }
  32191. scene.pushGeometry(torus, true);
  32192. return torus;
  32193. };
  32194. return Torus;
  32195. }(_Primitive));
  32196. Primitives.Torus = Torus;
  32197. var Ground = /** @class */ (function (_super) {
  32198. __extends(Ground, _super);
  32199. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32200. if (mesh === void 0) { mesh = null; }
  32201. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32202. _this.width = width;
  32203. _this.height = height;
  32204. _this.subdivisions = subdivisions;
  32205. return _this;
  32206. }
  32207. Ground.prototype._regenerateVertexData = function () {
  32208. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32209. };
  32210. Ground.prototype.copy = function (id) {
  32211. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32212. };
  32213. Ground.prototype.serialize = function () {
  32214. var serializationObject = _super.prototype.serialize.call(this);
  32215. serializationObject.width = this.width;
  32216. serializationObject.height = this.height;
  32217. serializationObject.subdivisions = this.subdivisions;
  32218. return serializationObject;
  32219. };
  32220. Ground.Parse = function (parsedGround, scene) {
  32221. if (scene.getGeometryByID(parsedGround.id)) {
  32222. return null; // null since geometry could be something else than a ground...
  32223. }
  32224. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32225. if (BABYLON.Tags) {
  32226. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32227. }
  32228. scene.pushGeometry(ground, true);
  32229. return ground;
  32230. };
  32231. return Ground;
  32232. }(_Primitive));
  32233. Primitives.Ground = Ground;
  32234. var TiledGround = /** @class */ (function (_super) {
  32235. __extends(TiledGround, _super);
  32236. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32237. if (mesh === void 0) { mesh = null; }
  32238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32239. _this.xmin = xmin;
  32240. _this.zmin = zmin;
  32241. _this.xmax = xmax;
  32242. _this.zmax = zmax;
  32243. _this.subdivisions = subdivisions;
  32244. _this.precision = precision;
  32245. return _this;
  32246. }
  32247. TiledGround.prototype._regenerateVertexData = function () {
  32248. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32249. };
  32250. TiledGround.prototype.copy = function (id) {
  32251. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32252. };
  32253. return TiledGround;
  32254. }(_Primitive));
  32255. Primitives.TiledGround = TiledGround;
  32256. var Plane = /** @class */ (function (_super) {
  32257. __extends(Plane, _super);
  32258. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32259. if (mesh === void 0) { mesh = null; }
  32260. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32262. _this.size = size;
  32263. _this.side = side;
  32264. return _this;
  32265. }
  32266. Plane.prototype._regenerateVertexData = function () {
  32267. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32268. };
  32269. Plane.prototype.copy = function (id) {
  32270. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32271. };
  32272. Plane.prototype.serialize = function () {
  32273. var serializationObject = _super.prototype.serialize.call(this);
  32274. serializationObject.size = this.size;
  32275. return serializationObject;
  32276. };
  32277. Plane.Parse = function (parsedPlane, scene) {
  32278. if (scene.getGeometryByID(parsedPlane.id)) {
  32279. return null; // null since geometry could be something else than a ground...
  32280. }
  32281. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32282. if (BABYLON.Tags) {
  32283. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32284. }
  32285. scene.pushGeometry(plane, true);
  32286. return plane;
  32287. };
  32288. return Plane;
  32289. }(_Primitive));
  32290. Primitives.Plane = Plane;
  32291. var TorusKnot = /** @class */ (function (_super) {
  32292. __extends(TorusKnot, _super);
  32293. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32294. if (mesh === void 0) { mesh = null; }
  32295. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32296. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32297. _this.radius = radius;
  32298. _this.tube = tube;
  32299. _this.radialSegments = radialSegments;
  32300. _this.tubularSegments = tubularSegments;
  32301. _this.p = p;
  32302. _this.q = q;
  32303. _this.side = side;
  32304. return _this;
  32305. }
  32306. TorusKnot.prototype._regenerateVertexData = function () {
  32307. 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 });
  32308. };
  32309. TorusKnot.prototype.copy = function (id) {
  32310. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32311. };
  32312. TorusKnot.prototype.serialize = function () {
  32313. var serializationObject = _super.prototype.serialize.call(this);
  32314. serializationObject.radius = this.radius;
  32315. serializationObject.tube = this.tube;
  32316. serializationObject.radialSegments = this.radialSegments;
  32317. serializationObject.tubularSegments = this.tubularSegments;
  32318. serializationObject.p = this.p;
  32319. serializationObject.q = this.q;
  32320. return serializationObject;
  32321. };
  32322. ;
  32323. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32324. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32325. return null; // null since geometry could be something else than a ground...
  32326. }
  32327. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32328. if (BABYLON.Tags) {
  32329. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32330. }
  32331. scene.pushGeometry(torusKnot, true);
  32332. return torusKnot;
  32333. };
  32334. return TorusKnot;
  32335. }(_Primitive));
  32336. Primitives.TorusKnot = TorusKnot;
  32337. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32338. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32339. })(BABYLON || (BABYLON = {}));
  32340. //# sourceMappingURL=babylon.geometry.js.map
  32341. var BABYLON;
  32342. (function (BABYLON) {
  32343. var PostProcessManager = /** @class */ (function () {
  32344. function PostProcessManager(scene) {
  32345. this._vertexBuffers = {};
  32346. this._scene = scene;
  32347. }
  32348. PostProcessManager.prototype._prepareBuffers = function () {
  32349. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32350. return;
  32351. }
  32352. // VBO
  32353. var vertices = [];
  32354. vertices.push(1, 1);
  32355. vertices.push(-1, 1);
  32356. vertices.push(-1, -1);
  32357. vertices.push(1, -1);
  32358. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32359. this._buildIndexBuffer();
  32360. };
  32361. PostProcessManager.prototype._buildIndexBuffer = function () {
  32362. // Indices
  32363. var indices = [];
  32364. indices.push(0);
  32365. indices.push(1);
  32366. indices.push(2);
  32367. indices.push(0);
  32368. indices.push(2);
  32369. indices.push(3);
  32370. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32371. };
  32372. PostProcessManager.prototype._rebuild = function () {
  32373. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32374. if (!vb) {
  32375. return;
  32376. }
  32377. vb._rebuild();
  32378. this._buildIndexBuffer();
  32379. };
  32380. // Methods
  32381. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32382. if (sourceTexture === void 0) { sourceTexture = null; }
  32383. if (postProcesses === void 0) { postProcesses = null; }
  32384. var camera = this._scene.activeCamera;
  32385. if (!camera) {
  32386. return false;
  32387. }
  32388. var postProcesses = postProcesses || camera._postProcesses;
  32389. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32390. return false;
  32391. }
  32392. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32393. return true;
  32394. };
  32395. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32396. if (targetTexture === void 0) { targetTexture = null; }
  32397. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32398. if (!this._scene.activeCamera) {
  32399. return;
  32400. }
  32401. var engine = this._scene.getEngine();
  32402. for (var index = 0; index < postProcesses.length; index++) {
  32403. if (index < postProcesses.length - 1) {
  32404. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32405. }
  32406. else {
  32407. if (targetTexture) {
  32408. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32409. }
  32410. else {
  32411. engine.restoreDefaultFramebuffer();
  32412. }
  32413. }
  32414. var pp = postProcesses[index];
  32415. var effect = pp.apply();
  32416. if (effect) {
  32417. pp.onBeforeRenderObservable.notifyObservers(effect);
  32418. // VBOs
  32419. this._prepareBuffers();
  32420. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32421. // Draw order
  32422. engine.draw(true, 0, 6);
  32423. pp.onAfterRenderObservable.notifyObservers(effect);
  32424. }
  32425. }
  32426. // Restore depth buffer
  32427. engine.setDepthBuffer(true);
  32428. engine.setDepthWrite(true);
  32429. };
  32430. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32431. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32432. var camera = this._scene.activeCamera;
  32433. if (!camera) {
  32434. return;
  32435. }
  32436. postProcesses = postProcesses || camera._postProcesses;
  32437. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32438. return;
  32439. }
  32440. var engine = this._scene.getEngine();
  32441. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32442. if (index < len - 1) {
  32443. postProcesses[index + 1].activate(camera, targetTexture);
  32444. }
  32445. else {
  32446. if (targetTexture) {
  32447. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32448. }
  32449. else {
  32450. engine.restoreDefaultFramebuffer();
  32451. }
  32452. }
  32453. if (doNotPresent) {
  32454. break;
  32455. }
  32456. var pp = postProcesses[index];
  32457. var effect = pp.apply();
  32458. if (effect) {
  32459. pp.onBeforeRenderObservable.notifyObservers(effect);
  32460. // VBOs
  32461. this._prepareBuffers();
  32462. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32463. // Draw order
  32464. engine.draw(true, 0, 6);
  32465. pp.onAfterRenderObservable.notifyObservers(effect);
  32466. }
  32467. }
  32468. // Restore states
  32469. engine.setDepthBuffer(true);
  32470. engine.setDepthWrite(true);
  32471. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32472. };
  32473. PostProcessManager.prototype.dispose = function () {
  32474. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32475. if (buffer) {
  32476. buffer.dispose();
  32477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32478. }
  32479. if (this._indexBuffer) {
  32480. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32481. this._indexBuffer = null;
  32482. }
  32483. };
  32484. return PostProcessManager;
  32485. }());
  32486. BABYLON.PostProcessManager = PostProcessManager;
  32487. })(BABYLON || (BABYLON = {}));
  32488. //# sourceMappingURL=babylon.postProcessManager.js.map
  32489. var BABYLON;
  32490. (function (BABYLON) {
  32491. /**
  32492. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32493. */
  32494. var PerformanceMonitor = /** @class */ (function () {
  32495. /**
  32496. * constructor
  32497. * @param frameSampleSize The number of samples required to saturate the sliding window
  32498. */
  32499. function PerformanceMonitor(frameSampleSize) {
  32500. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32501. this._enabled = true;
  32502. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32503. }
  32504. /**
  32505. * Samples current frame
  32506. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32507. */
  32508. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32509. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32510. if (!this._enabled)
  32511. return;
  32512. if (this._lastFrameTimeMs != null) {
  32513. var dt = timeMs - this._lastFrameTimeMs;
  32514. this._rollingFrameTime.add(dt);
  32515. }
  32516. this._lastFrameTimeMs = timeMs;
  32517. };
  32518. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32519. /**
  32520. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32521. * @return Average frame time in milliseconds
  32522. */
  32523. get: function () {
  32524. return this._rollingFrameTime.average;
  32525. },
  32526. enumerable: true,
  32527. configurable: true
  32528. });
  32529. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32530. /**
  32531. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32532. * @return Frame time variance in milliseconds squared
  32533. */
  32534. get: function () {
  32535. return this._rollingFrameTime.variance;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32541. /**
  32542. * Returns the frame time of the most recent frame
  32543. * @return Frame time in milliseconds
  32544. */
  32545. get: function () {
  32546. return this._rollingFrameTime.history(0);
  32547. },
  32548. enumerable: true,
  32549. configurable: true
  32550. });
  32551. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32552. /**
  32553. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32554. * @return Framerate in frames per second
  32555. */
  32556. get: function () {
  32557. return 1000.0 / this._rollingFrameTime.average;
  32558. },
  32559. enumerable: true,
  32560. configurable: true
  32561. });
  32562. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32563. /**
  32564. * Returns the average framerate in frames per second using the most recent frame time
  32565. * @return Framerate in frames per second
  32566. */
  32567. get: function () {
  32568. var history = this._rollingFrameTime.history(0);
  32569. if (history === 0) {
  32570. return 0;
  32571. }
  32572. return 1000.0 / history;
  32573. },
  32574. enumerable: true,
  32575. configurable: true
  32576. });
  32577. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32578. /**
  32579. * Returns true if enough samples have been taken to completely fill the sliding window
  32580. * @return true if saturated
  32581. */
  32582. get: function () {
  32583. return this._rollingFrameTime.isSaturated();
  32584. },
  32585. enumerable: true,
  32586. configurable: true
  32587. });
  32588. /**
  32589. * Enables contributions to the sliding window sample set
  32590. */
  32591. PerformanceMonitor.prototype.enable = function () {
  32592. this._enabled = true;
  32593. };
  32594. /**
  32595. * Disables contributions to the sliding window sample set
  32596. * Samples will not be interpolated over the disabled period
  32597. */
  32598. PerformanceMonitor.prototype.disable = function () {
  32599. this._enabled = false;
  32600. //clear last sample to avoid interpolating over the disabled period when next enabled
  32601. this._lastFrameTimeMs = null;
  32602. };
  32603. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32604. /**
  32605. * Returns true if sampling is enabled
  32606. * @return true if enabled
  32607. */
  32608. get: function () {
  32609. return this._enabled;
  32610. },
  32611. enumerable: true,
  32612. configurable: true
  32613. });
  32614. /**
  32615. * Resets performance monitor
  32616. */
  32617. PerformanceMonitor.prototype.reset = function () {
  32618. //clear last sample to avoid interpolating over the disabled period when next enabled
  32619. this._lastFrameTimeMs = null;
  32620. //wipe record
  32621. this._rollingFrameTime.reset();
  32622. };
  32623. return PerformanceMonitor;
  32624. }());
  32625. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32626. /**
  32627. * RollingAverage
  32628. *
  32629. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32630. */
  32631. var RollingAverage = /** @class */ (function () {
  32632. /**
  32633. * constructor
  32634. * @param length The number of samples required to saturate the sliding window
  32635. */
  32636. function RollingAverage(length) {
  32637. this._samples = new Array(length);
  32638. this.reset();
  32639. }
  32640. /**
  32641. * Adds a sample to the sample set
  32642. * @param v The sample value
  32643. */
  32644. RollingAverage.prototype.add = function (v) {
  32645. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32646. var delta;
  32647. //we need to check if we've already wrapped round
  32648. if (this.isSaturated()) {
  32649. //remove bottom of stack from mean
  32650. var bottomValue = this._samples[this._pos];
  32651. delta = bottomValue - this.average;
  32652. this.average -= delta / (this._sampleCount - 1);
  32653. this._m2 -= delta * (bottomValue - this.average);
  32654. }
  32655. else {
  32656. this._sampleCount++;
  32657. }
  32658. //add new value to mean
  32659. delta = v - this.average;
  32660. this.average += delta / (this._sampleCount);
  32661. this._m2 += delta * (v - this.average);
  32662. //set the new variance
  32663. this.variance = this._m2 / (this._sampleCount - 1);
  32664. this._samples[this._pos] = v;
  32665. this._pos++;
  32666. this._pos %= this._samples.length; //positive wrap around
  32667. };
  32668. /**
  32669. * Returns previously added values or null if outside of history or outside the sliding window domain
  32670. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32671. * @return Value previously recorded with add() or null if outside of range
  32672. */
  32673. RollingAverage.prototype.history = function (i) {
  32674. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32675. return 0;
  32676. }
  32677. var i0 = this._wrapPosition(this._pos - 1.0);
  32678. return this._samples[this._wrapPosition(i0 - i)];
  32679. };
  32680. /**
  32681. * Returns true if enough samples have been taken to completely fill the sliding window
  32682. * @return true if sample-set saturated
  32683. */
  32684. RollingAverage.prototype.isSaturated = function () {
  32685. return this._sampleCount >= this._samples.length;
  32686. };
  32687. /**
  32688. * Resets the rolling average (equivalent to 0 samples taken so far)
  32689. */
  32690. RollingAverage.prototype.reset = function () {
  32691. this.average = 0;
  32692. this.variance = 0;
  32693. this._sampleCount = 0;
  32694. this._pos = 0;
  32695. this._m2 = 0;
  32696. };
  32697. /**
  32698. * Wraps a value around the sample range boundaries
  32699. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32700. * @return Wrapped position in sample range
  32701. */
  32702. RollingAverage.prototype._wrapPosition = function (i) {
  32703. var max = this._samples.length;
  32704. return ((i % max) + max) % max;
  32705. };
  32706. return RollingAverage;
  32707. }());
  32708. BABYLON.RollingAverage = RollingAverage;
  32709. })(BABYLON || (BABYLON = {}));
  32710. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32711. var BABYLON;
  32712. (function (BABYLON) {
  32713. /**
  32714. * This groups together the common properties used for image processing either in direct forward pass
  32715. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32716. * or not.
  32717. */
  32718. var ImageProcessingConfiguration = /** @class */ (function () {
  32719. function ImageProcessingConfiguration() {
  32720. /**
  32721. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32722. */
  32723. this.colorCurves = new BABYLON.ColorCurves();
  32724. this._colorCurvesEnabled = false;
  32725. this._colorGradingEnabled = false;
  32726. this._colorGradingWithGreenDepth = true;
  32727. this._colorGradingBGR = true;
  32728. this._exposure = 1.0;
  32729. this._toneMappingEnabled = false;
  32730. this._contrast = 1.0;
  32731. /**
  32732. * Vignette stretch size.
  32733. */
  32734. this.vignetteStretch = 0;
  32735. /**
  32736. * Vignette centre X Offset.
  32737. */
  32738. this.vignetteCentreX = 0;
  32739. /**
  32740. * Vignette centre Y Offset.
  32741. */
  32742. this.vignetteCentreY = 0;
  32743. /**
  32744. * Vignette weight or intensity of the vignette effect.
  32745. */
  32746. this.vignetteWeight = 1.5;
  32747. /**
  32748. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32749. * if vignetteEnabled is set to true.
  32750. */
  32751. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32752. /**
  32753. * Camera field of view used by the Vignette effect.
  32754. */
  32755. this.vignetteCameraFov = 0.5;
  32756. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32757. this._vignetteEnabled = false;
  32758. this._applyByPostProcess = false;
  32759. this._isEnabled = true;
  32760. /**
  32761. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32762. * @type {BABYLON.Observable}
  32763. */
  32764. this.onUpdateParameters = new BABYLON.Observable();
  32765. }
  32766. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32767. /**
  32768. * Gets wether the color curves effect is enabled.
  32769. */
  32770. get: function () {
  32771. return this._colorCurvesEnabled;
  32772. },
  32773. /**
  32774. * Sets wether the color curves effect is enabled.
  32775. */
  32776. set: function (value) {
  32777. if (this._colorCurvesEnabled === value) {
  32778. return;
  32779. }
  32780. this._colorCurvesEnabled = value;
  32781. this._updateParameters();
  32782. },
  32783. enumerable: true,
  32784. configurable: true
  32785. });
  32786. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32787. /**
  32788. * Gets wether the color grading effect is enabled.
  32789. */
  32790. get: function () {
  32791. return this._colorGradingEnabled;
  32792. },
  32793. /**
  32794. * Sets wether the color grading effect is enabled.
  32795. */
  32796. set: function (value) {
  32797. if (this._colorGradingEnabled === value) {
  32798. return;
  32799. }
  32800. this._colorGradingEnabled = value;
  32801. this._updateParameters();
  32802. },
  32803. enumerable: true,
  32804. configurable: true
  32805. });
  32806. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32807. /**
  32808. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32809. */
  32810. get: function () {
  32811. return this._colorGradingWithGreenDepth;
  32812. },
  32813. /**
  32814. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32815. */
  32816. set: function (value) {
  32817. if (this._colorGradingWithGreenDepth === value) {
  32818. return;
  32819. }
  32820. this._colorGradingWithGreenDepth = value;
  32821. this._updateParameters();
  32822. },
  32823. enumerable: true,
  32824. configurable: true
  32825. });
  32826. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32827. /**
  32828. * Gets wether the color grading texture contains BGR values.
  32829. */
  32830. get: function () {
  32831. return this._colorGradingBGR;
  32832. },
  32833. /**
  32834. * Sets wether the color grading texture contains BGR values.
  32835. */
  32836. set: function (value) {
  32837. if (this._colorGradingBGR === value) {
  32838. return;
  32839. }
  32840. this._colorGradingBGR = value;
  32841. this._updateParameters();
  32842. },
  32843. enumerable: true,
  32844. configurable: true
  32845. });
  32846. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32847. /**
  32848. * Gets the Exposure used in the effect.
  32849. */
  32850. get: function () {
  32851. return this._exposure;
  32852. },
  32853. /**
  32854. * Sets the Exposure used in the effect.
  32855. */
  32856. set: function (value) {
  32857. if (this._exposure === value) {
  32858. return;
  32859. }
  32860. this._exposure = value;
  32861. this._updateParameters();
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32867. /**
  32868. * Gets wether the tone mapping effect is enabled.
  32869. */
  32870. get: function () {
  32871. return this._toneMappingEnabled;
  32872. },
  32873. /**
  32874. * Sets wether the tone mapping effect is enabled.
  32875. */
  32876. set: function (value) {
  32877. if (this._toneMappingEnabled === value) {
  32878. return;
  32879. }
  32880. this._toneMappingEnabled = value;
  32881. this._updateParameters();
  32882. },
  32883. enumerable: true,
  32884. configurable: true
  32885. });
  32886. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32887. /**
  32888. * Gets the contrast used in the effect.
  32889. */
  32890. get: function () {
  32891. return this._contrast;
  32892. },
  32893. /**
  32894. * Sets the contrast used in the effect.
  32895. */
  32896. set: function (value) {
  32897. if (this._contrast === value) {
  32898. return;
  32899. }
  32900. this._contrast = value;
  32901. this._updateParameters();
  32902. },
  32903. enumerable: true,
  32904. configurable: true
  32905. });
  32906. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32907. /**
  32908. * Gets the vignette blend mode allowing different kind of effect.
  32909. */
  32910. get: function () {
  32911. return this._vignetteBlendMode;
  32912. },
  32913. /**
  32914. * Sets the vignette blend mode allowing different kind of effect.
  32915. */
  32916. set: function (value) {
  32917. if (this._vignetteBlendMode === value) {
  32918. return;
  32919. }
  32920. this._vignetteBlendMode = value;
  32921. this._updateParameters();
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32927. /**
  32928. * Gets wether the vignette effect is enabled.
  32929. */
  32930. get: function () {
  32931. return this._vignetteEnabled;
  32932. },
  32933. /**
  32934. * Sets wether the vignette effect is enabled.
  32935. */
  32936. set: function (value) {
  32937. if (this._vignetteEnabled === value) {
  32938. return;
  32939. }
  32940. this._vignetteEnabled = value;
  32941. this._updateParameters();
  32942. },
  32943. enumerable: true,
  32944. configurable: true
  32945. });
  32946. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32947. /**
  32948. * Gets wether the image processing is applied through a post process or not.
  32949. */
  32950. get: function () {
  32951. return this._applyByPostProcess;
  32952. },
  32953. /**
  32954. * Sets wether the image processing is applied through a post process or not.
  32955. */
  32956. set: function (value) {
  32957. if (this._applyByPostProcess === value) {
  32958. return;
  32959. }
  32960. this._applyByPostProcess = value;
  32961. this._updateParameters();
  32962. },
  32963. enumerable: true,
  32964. configurable: true
  32965. });
  32966. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32967. /**
  32968. * Gets wether the image processing is enabled or not.
  32969. */
  32970. get: function () {
  32971. return this._isEnabled;
  32972. },
  32973. /**
  32974. * Sets wether the image processing is enabled or not.
  32975. */
  32976. set: function (value) {
  32977. if (this._isEnabled === value) {
  32978. return;
  32979. }
  32980. this._isEnabled = value;
  32981. this._updateParameters();
  32982. },
  32983. enumerable: true,
  32984. configurable: true
  32985. });
  32986. /**
  32987. * Method called each time the image processing information changes requires to recompile the effect.
  32988. */
  32989. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32990. this.onUpdateParameters.notifyObservers(this);
  32991. };
  32992. ImageProcessingConfiguration.prototype.getClassName = function () {
  32993. return "ImageProcessingConfiguration";
  32994. };
  32995. /**
  32996. * Prepare the list of uniforms associated with the Image Processing effects.
  32997. * @param uniformsList The list of uniforms used in the effect
  32998. * @param defines the list of defines currently in use
  32999. */
  33000. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33001. if (defines.EXPOSURE) {
  33002. uniforms.push("exposureLinear");
  33003. }
  33004. if (defines.CONTRAST) {
  33005. uniforms.push("contrast");
  33006. }
  33007. if (defines.COLORGRADING) {
  33008. uniforms.push("colorTransformSettings");
  33009. }
  33010. if (defines.VIGNETTE) {
  33011. uniforms.push("vInverseScreenSize");
  33012. uniforms.push("vignetteSettings1");
  33013. uniforms.push("vignetteSettings2");
  33014. }
  33015. if (defines.COLORCURVES) {
  33016. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33017. }
  33018. };
  33019. /**
  33020. * Prepare the list of samplers associated with the Image Processing effects.
  33021. * @param uniformsList The list of uniforms used in the effect
  33022. * @param defines the list of defines currently in use
  33023. */
  33024. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33025. if (defines.COLORGRADING) {
  33026. samplersList.push("txColorTransform");
  33027. }
  33028. };
  33029. /**
  33030. * Prepare the list of defines associated to the shader.
  33031. * @param defines the list of defines to complete
  33032. */
  33033. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33034. if (forPostProcess === void 0) { forPostProcess = false; }
  33035. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33036. defines.VIGNETTE = false;
  33037. defines.TONEMAPPING = false;
  33038. defines.CONTRAST = false;
  33039. defines.EXPOSURE = false;
  33040. defines.COLORCURVES = false;
  33041. defines.COLORGRADING = false;
  33042. defines.COLORGRADING3D = false;
  33043. defines.IMAGEPROCESSING = false;
  33044. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33045. return;
  33046. }
  33047. defines.VIGNETTE = this.vignetteEnabled;
  33048. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33049. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33050. defines.TONEMAPPING = this.toneMappingEnabled;
  33051. defines.CONTRAST = (this.contrast !== 1.0);
  33052. defines.EXPOSURE = (this.exposure !== 1.0);
  33053. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33054. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33055. if (defines.COLORGRADING) {
  33056. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33057. }
  33058. else {
  33059. defines.COLORGRADING3D = false;
  33060. }
  33061. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33062. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33063. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33064. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33065. };
  33066. /**
  33067. * Returns true if all the image processing information are ready.
  33068. */
  33069. ImageProcessingConfiguration.prototype.isReady = function () {
  33070. // Color Grading texure can not be none blocking.
  33071. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33072. };
  33073. /**
  33074. * Binds the image processing to the shader.
  33075. * @param effect The effect to bind to
  33076. */
  33077. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33078. if (aspectRatio === void 0) { aspectRatio = 1; }
  33079. // Color Curves
  33080. if (this._colorCurvesEnabled && this.colorCurves) {
  33081. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33082. }
  33083. // Vignette
  33084. if (this._vignetteEnabled) {
  33085. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33086. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33087. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33088. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33089. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33090. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33091. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33092. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33093. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33094. var vignettePower = -2.0 * this.vignetteWeight;
  33095. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33096. }
  33097. // Exposure
  33098. effect.setFloat("exposureLinear", this.exposure);
  33099. // Contrast
  33100. effect.setFloat("contrast", this.contrast);
  33101. // Color transform settings
  33102. if (this.colorGradingTexture) {
  33103. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33104. var textureSize = this.colorGradingTexture.getSize().height;
  33105. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33106. 0.5 / textureSize, // textureOffset
  33107. textureSize, // textureSize
  33108. this.colorGradingTexture.level // weight
  33109. );
  33110. }
  33111. };
  33112. /**
  33113. * Clones the current image processing instance.
  33114. * @return The cloned image processing
  33115. */
  33116. ImageProcessingConfiguration.prototype.clone = function () {
  33117. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33118. };
  33119. /**
  33120. * Serializes the current image processing instance to a json representation.
  33121. * @return a JSON representation
  33122. */
  33123. ImageProcessingConfiguration.prototype.serialize = function () {
  33124. return BABYLON.SerializationHelper.Serialize(this);
  33125. };
  33126. /**
  33127. * Parses the image processing from a json representation.
  33128. * @param source the JSON source to parse
  33129. * @return The parsed image processing
  33130. */
  33131. ImageProcessingConfiguration.Parse = function (source) {
  33132. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33133. };
  33134. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33135. /**
  33136. * Used to apply the vignette as a mix with the pixel color.
  33137. */
  33138. get: function () {
  33139. return this._VIGNETTEMODE_MULTIPLY;
  33140. },
  33141. enumerable: true,
  33142. configurable: true
  33143. });
  33144. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33145. /**
  33146. * Used to apply the vignette as a replacement of the pixel color.
  33147. */
  33148. get: function () {
  33149. return this._VIGNETTEMODE_OPAQUE;
  33150. },
  33151. enumerable: true,
  33152. configurable: true
  33153. });
  33154. // Static constants associated to the image processing.
  33155. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33156. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33157. __decorate([
  33158. BABYLON.serializeAsColorCurves()
  33159. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33160. __decorate([
  33161. BABYLON.serialize()
  33162. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33163. __decorate([
  33164. BABYLON.serializeAsTexture()
  33165. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33166. __decorate([
  33167. BABYLON.serialize()
  33168. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33169. __decorate([
  33170. BABYLON.serialize()
  33171. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33172. __decorate([
  33173. BABYLON.serialize()
  33174. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33175. __decorate([
  33176. BABYLON.serialize()
  33177. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33178. __decorate([
  33179. BABYLON.serialize()
  33180. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33181. __decorate([
  33182. BABYLON.serialize()
  33183. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33184. __decorate([
  33185. BABYLON.serialize()
  33186. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33187. __decorate([
  33188. BABYLON.serialize()
  33189. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33190. __decorate([
  33191. BABYLON.serialize()
  33192. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33193. __decorate([
  33194. BABYLON.serialize()
  33195. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33196. __decorate([
  33197. BABYLON.serializeAsColor4()
  33198. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33199. __decorate([
  33200. BABYLON.serialize()
  33201. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33202. __decorate([
  33203. BABYLON.serialize()
  33204. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33205. __decorate([
  33206. BABYLON.serialize()
  33207. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33208. __decorate([
  33209. BABYLON.serialize()
  33210. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33211. __decorate([
  33212. BABYLON.serialize()
  33213. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33214. return ImageProcessingConfiguration;
  33215. }());
  33216. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33217. })(BABYLON || (BABYLON = {}));
  33218. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33219. var BABYLON;
  33220. (function (BABYLON) {
  33221. /**
  33222. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33223. * It can help converting any input color in a desired output one. This can then be used to create effects
  33224. * from sepia, black and white to sixties or futuristic rendering...
  33225. *
  33226. * The only supported format is currently 3dl.
  33227. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33228. */
  33229. var ColorGradingTexture = /** @class */ (function (_super) {
  33230. __extends(ColorGradingTexture, _super);
  33231. /**
  33232. * Instantiates a ColorGradingTexture from the following parameters.
  33233. *
  33234. * @param url The location of the color gradind data (currently only supporting 3dl)
  33235. * @param scene The scene the texture will be used in
  33236. */
  33237. function ColorGradingTexture(url, scene) {
  33238. var _this = _super.call(this, scene) || this;
  33239. if (!url) {
  33240. return _this;
  33241. }
  33242. _this._engine = scene.getEngine();
  33243. _this._textureMatrix = BABYLON.Matrix.Identity();
  33244. _this.name = url;
  33245. _this.url = url;
  33246. _this.hasAlpha = false;
  33247. _this.isCube = false;
  33248. _this.is3D = _this._engine.webGLVersion > 1;
  33249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33251. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33252. _this.anisotropicFilteringLevel = 1;
  33253. _this._texture = _this._getFromCache(url, true);
  33254. if (!_this._texture) {
  33255. if (!scene.useDelayedTextureLoading) {
  33256. _this.loadTexture();
  33257. }
  33258. else {
  33259. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33260. }
  33261. }
  33262. return _this;
  33263. }
  33264. /**
  33265. * Returns the texture matrix used in most of the material.
  33266. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33267. */
  33268. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33269. return this._textureMatrix;
  33270. };
  33271. /**
  33272. * Occurs when the file being loaded is a .3dl LUT file.
  33273. */
  33274. ColorGradingTexture.prototype.load3dlTexture = function () {
  33275. var engine = this._engine;
  33276. var texture;
  33277. if (engine.webGLVersion === 1) {
  33278. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33279. }
  33280. else {
  33281. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33282. }
  33283. this._texture = texture;
  33284. var callback = function (text) {
  33285. if (typeof text !== "string") {
  33286. return;
  33287. }
  33288. var data = null;
  33289. var tempData = null;
  33290. var line;
  33291. var lines = text.split('\n');
  33292. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33293. var maxColor = 0;
  33294. for (var i = 0; i < lines.length; i++) {
  33295. line = lines[i];
  33296. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33297. continue;
  33298. if (line.indexOf('#') === 0)
  33299. continue;
  33300. var words = line.split(" ");
  33301. if (size === 0) {
  33302. // Number of space + one
  33303. size = words.length;
  33304. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33305. tempData = new Float32Array(size * size * size * 4);
  33306. continue;
  33307. }
  33308. if (size != 0) {
  33309. var r = Math.max(parseInt(words[0]), 0);
  33310. var g = Math.max(parseInt(words[1]), 0);
  33311. var b = Math.max(parseInt(words[2]), 0);
  33312. maxColor = Math.max(r, maxColor);
  33313. maxColor = Math.max(g, maxColor);
  33314. maxColor = Math.max(b, maxColor);
  33315. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33316. if (tempData) {
  33317. tempData[pixelStorageIndex + 0] = r;
  33318. tempData[pixelStorageIndex + 1] = g;
  33319. tempData[pixelStorageIndex + 2] = b;
  33320. }
  33321. pixelIndexSlice++;
  33322. if (pixelIndexSlice % size == 0) {
  33323. pixelIndexH++;
  33324. pixelIndexSlice = 0;
  33325. if (pixelIndexH % size == 0) {
  33326. pixelIndexW++;
  33327. pixelIndexH = 0;
  33328. }
  33329. }
  33330. }
  33331. }
  33332. if (tempData && data) {
  33333. for (var i = 0; i < tempData.length; i++) {
  33334. if (i > 0 && (i + 1) % 4 === 0) {
  33335. data[i] = 255;
  33336. }
  33337. else {
  33338. var value = tempData[i];
  33339. data[i] = (value / maxColor * 255);
  33340. }
  33341. }
  33342. }
  33343. if (texture.is3D) {
  33344. texture.updateSize(size, size, size);
  33345. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33346. }
  33347. else {
  33348. texture.updateSize(size * size, size);
  33349. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33350. }
  33351. };
  33352. BABYLON.Tools.LoadFile(this.url, callback);
  33353. return this._texture;
  33354. };
  33355. /**
  33356. * Starts the loading process of the texture.
  33357. */
  33358. ColorGradingTexture.prototype.loadTexture = function () {
  33359. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33360. this.load3dlTexture();
  33361. }
  33362. };
  33363. /**
  33364. * Clones the color gradind texture.
  33365. */
  33366. ColorGradingTexture.prototype.clone = function () {
  33367. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33368. // Base texture
  33369. newTexture.level = this.level;
  33370. return newTexture;
  33371. };
  33372. /**
  33373. * Called during delayed load for textures.
  33374. */
  33375. ColorGradingTexture.prototype.delayLoad = function () {
  33376. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33377. return;
  33378. }
  33379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33380. this._texture = this._getFromCache(this.url, true);
  33381. if (!this._texture) {
  33382. this.loadTexture();
  33383. }
  33384. };
  33385. /**
  33386. * Parses a color grading texture serialized by Babylon.
  33387. * @param parsedTexture The texture information being parsedTexture
  33388. * @param scene The scene to load the texture in
  33389. * @param rootUrl The root url of the data assets to load
  33390. * @return A color gradind texture
  33391. */
  33392. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33393. var texture = null;
  33394. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33395. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33396. texture.name = parsedTexture.name;
  33397. texture.level = parsedTexture.level;
  33398. }
  33399. return texture;
  33400. };
  33401. /**
  33402. * Serializes the LUT texture to json format.
  33403. */
  33404. ColorGradingTexture.prototype.serialize = function () {
  33405. if (!this.name) {
  33406. return null;
  33407. }
  33408. var serializationObject = {};
  33409. serializationObject.name = this.name;
  33410. serializationObject.level = this.level;
  33411. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33412. return serializationObject;
  33413. };
  33414. /**
  33415. * Empty line regex stored for GC.
  33416. */
  33417. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33418. return ColorGradingTexture;
  33419. }(BABYLON.BaseTexture));
  33420. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33421. })(BABYLON || (BABYLON = {}));
  33422. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33423. var BABYLON;
  33424. (function (BABYLON) {
  33425. /**
  33426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33428. * 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;
  33429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33430. */
  33431. var ColorCurves = /** @class */ (function () {
  33432. function ColorCurves() {
  33433. this._dirty = true;
  33434. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33435. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33436. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33437. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33438. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33439. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33440. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33441. this._globalHue = 30;
  33442. this._globalDensity = 0;
  33443. this._globalSaturation = 0;
  33444. this._globalExposure = 0;
  33445. this._highlightsHue = 30;
  33446. this._highlightsDensity = 0;
  33447. this._highlightsSaturation = 0;
  33448. this._highlightsExposure = 0;
  33449. this._midtonesHue = 30;
  33450. this._midtonesDensity = 0;
  33451. this._midtonesSaturation = 0;
  33452. this._midtonesExposure = 0;
  33453. this._shadowsHue = 30;
  33454. this._shadowsDensity = 0;
  33455. this._shadowsSaturation = 0;
  33456. this._shadowsExposure = 0;
  33457. }
  33458. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33459. /**
  33460. * Gets the global Hue value.
  33461. * 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).
  33462. */
  33463. get: function () {
  33464. return this._globalHue;
  33465. },
  33466. /**
  33467. * Sets the global Hue value.
  33468. * 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).
  33469. */
  33470. set: function (value) {
  33471. this._globalHue = value;
  33472. this._dirty = true;
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33478. /**
  33479. * Gets the global Density value.
  33480. * 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.
  33481. * Values less than zero provide a filter of opposite hue.
  33482. */
  33483. get: function () {
  33484. return this._globalDensity;
  33485. },
  33486. /**
  33487. * Sets the global Density value.
  33488. * 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.
  33489. * Values less than zero provide a filter of opposite hue.
  33490. */
  33491. set: function (value) {
  33492. this._globalDensity = value;
  33493. this._dirty = true;
  33494. },
  33495. enumerable: true,
  33496. configurable: true
  33497. });
  33498. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33499. /**
  33500. * Gets the global Saturation value.
  33501. * 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.
  33502. */
  33503. get: function () {
  33504. return this._globalSaturation;
  33505. },
  33506. /**
  33507. * Sets the global Saturation value.
  33508. * 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.
  33509. */
  33510. set: function (value) {
  33511. this._globalSaturation = value;
  33512. this._dirty = true;
  33513. },
  33514. enumerable: true,
  33515. configurable: true
  33516. });
  33517. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33518. /**
  33519. * Gets the highlights Hue value.
  33520. * 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).
  33521. */
  33522. get: function () {
  33523. return this._highlightsHue;
  33524. },
  33525. /**
  33526. * Sets the highlights Hue value.
  33527. * 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).
  33528. */
  33529. set: function (value) {
  33530. this._highlightsHue = value;
  33531. this._dirty = true;
  33532. },
  33533. enumerable: true,
  33534. configurable: true
  33535. });
  33536. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33537. /**
  33538. * Gets the highlights Density value.
  33539. * 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.
  33540. * Values less than zero provide a filter of opposite hue.
  33541. */
  33542. get: function () {
  33543. return this._highlightsDensity;
  33544. },
  33545. /**
  33546. * Sets the highlights Density value.
  33547. * 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.
  33548. * Values less than zero provide a filter of opposite hue.
  33549. */
  33550. set: function (value) {
  33551. this._highlightsDensity = value;
  33552. this._dirty = true;
  33553. },
  33554. enumerable: true,
  33555. configurable: true
  33556. });
  33557. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33558. /**
  33559. * Gets the highlights Saturation value.
  33560. * 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.
  33561. */
  33562. get: function () {
  33563. return this._highlightsSaturation;
  33564. },
  33565. /**
  33566. * Sets the highlights Saturation value.
  33567. * 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.
  33568. */
  33569. set: function (value) {
  33570. this._highlightsSaturation = value;
  33571. this._dirty = true;
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33577. /**
  33578. * Gets the highlights Exposure value.
  33579. * 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.
  33580. */
  33581. get: function () {
  33582. return this._highlightsExposure;
  33583. },
  33584. /**
  33585. * Sets the highlights Exposure value.
  33586. * 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.
  33587. */
  33588. set: function (value) {
  33589. this._highlightsExposure = value;
  33590. this._dirty = true;
  33591. },
  33592. enumerable: true,
  33593. configurable: true
  33594. });
  33595. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33596. /**
  33597. * Gets the midtones Hue value.
  33598. * 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).
  33599. */
  33600. get: function () {
  33601. return this._midtonesHue;
  33602. },
  33603. /**
  33604. * Sets the midtones Hue value.
  33605. * 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).
  33606. */
  33607. set: function (value) {
  33608. this._midtonesHue = value;
  33609. this._dirty = true;
  33610. },
  33611. enumerable: true,
  33612. configurable: true
  33613. });
  33614. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33615. /**
  33616. * Gets the midtones Density value.
  33617. * 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.
  33618. * Values less than zero provide a filter of opposite hue.
  33619. */
  33620. get: function () {
  33621. return this._midtonesDensity;
  33622. },
  33623. /**
  33624. * Sets the midtones Density value.
  33625. * 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.
  33626. * Values less than zero provide a filter of opposite hue.
  33627. */
  33628. set: function (value) {
  33629. this._midtonesDensity = value;
  33630. this._dirty = true;
  33631. },
  33632. enumerable: true,
  33633. configurable: true
  33634. });
  33635. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33636. /**
  33637. * Gets the midtones Saturation value.
  33638. * 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.
  33639. */
  33640. get: function () {
  33641. return this._midtonesSaturation;
  33642. },
  33643. /**
  33644. * Sets the midtones Saturation value.
  33645. * 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.
  33646. */
  33647. set: function (value) {
  33648. this._midtonesSaturation = value;
  33649. this._dirty = true;
  33650. },
  33651. enumerable: true,
  33652. configurable: true
  33653. });
  33654. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33655. /**
  33656. * Gets the midtones Exposure value.
  33657. * 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.
  33658. */
  33659. get: function () {
  33660. return this._midtonesExposure;
  33661. },
  33662. /**
  33663. * Sets the midtones Exposure value.
  33664. * 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.
  33665. */
  33666. set: function (value) {
  33667. this._midtonesExposure = value;
  33668. this._dirty = true;
  33669. },
  33670. enumerable: true,
  33671. configurable: true
  33672. });
  33673. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33674. /**
  33675. * Gets the shadows Hue value.
  33676. * 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).
  33677. */
  33678. get: function () {
  33679. return this._shadowsHue;
  33680. },
  33681. /**
  33682. * Sets the shadows Hue value.
  33683. * 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).
  33684. */
  33685. set: function (value) {
  33686. this._shadowsHue = value;
  33687. this._dirty = true;
  33688. },
  33689. enumerable: true,
  33690. configurable: true
  33691. });
  33692. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33693. /**
  33694. * Gets the shadows Density value.
  33695. * 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.
  33696. * Values less than zero provide a filter of opposite hue.
  33697. */
  33698. get: function () {
  33699. return this._shadowsDensity;
  33700. },
  33701. /**
  33702. * Sets the shadows Density value.
  33703. * 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.
  33704. * Values less than zero provide a filter of opposite hue.
  33705. */
  33706. set: function (value) {
  33707. this._shadowsDensity = value;
  33708. this._dirty = true;
  33709. },
  33710. enumerable: true,
  33711. configurable: true
  33712. });
  33713. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33714. /**
  33715. * Gets the shadows Saturation value.
  33716. * 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.
  33717. */
  33718. get: function () {
  33719. return this._shadowsSaturation;
  33720. },
  33721. /**
  33722. * Sets the shadows Saturation value.
  33723. * 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.
  33724. */
  33725. set: function (value) {
  33726. this._shadowsSaturation = value;
  33727. this._dirty = true;
  33728. },
  33729. enumerable: true,
  33730. configurable: true
  33731. });
  33732. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33733. /**
  33734. * Gets the shadows Exposure value.
  33735. * 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.
  33736. */
  33737. get: function () {
  33738. return this._shadowsExposure;
  33739. },
  33740. /**
  33741. * Sets the shadows Exposure value.
  33742. * 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.
  33743. */
  33744. set: function (value) {
  33745. this._shadowsExposure = value;
  33746. this._dirty = true;
  33747. },
  33748. enumerable: true,
  33749. configurable: true
  33750. });
  33751. ColorCurves.prototype.getClassName = function () {
  33752. return "ColorCurves";
  33753. };
  33754. /**
  33755. * Binds the color curves to the shader.
  33756. * @param colorCurves The color curve to bind
  33757. * @param effect The effect to bind to
  33758. */
  33759. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33760. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33761. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33762. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33763. if (colorCurves._dirty) {
  33764. colorCurves._dirty = false;
  33765. // Fill in global info.
  33766. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33767. // Compute highlights info.
  33768. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33769. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33770. // Compute midtones info.
  33771. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33772. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33773. // Compute shadows info.
  33774. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33775. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33776. // Compute deltas (neutral is midtones).
  33777. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33778. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33779. }
  33780. if (effect) {
  33781. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33782. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33783. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33784. }
  33785. };
  33786. /**
  33787. * Prepare the list of uniforms associated with the ColorCurves effects.
  33788. * @param uniformsList The list of uniforms used in the effect
  33789. */
  33790. ColorCurves.PrepareUniforms = function (uniformsList) {
  33791. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33792. };
  33793. /**
  33794. * Returns color grading data based on a hue, density, saturation and exposure value.
  33795. * @param filterHue The hue of the color filter.
  33796. * @param filterDensity The density of the color filter.
  33797. * @param saturation The saturation.
  33798. * @param exposure The exposure.
  33799. * @param result The result data container.
  33800. */
  33801. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33802. if (hue == null) {
  33803. return;
  33804. }
  33805. hue = ColorCurves.clamp(hue, 0, 360);
  33806. density = ColorCurves.clamp(density, -100, 100);
  33807. saturation = ColorCurves.clamp(saturation, -100, 100);
  33808. exposure = ColorCurves.clamp(exposure, -100, 100);
  33809. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33810. // so that the maximum filter density is only 50% control. This provides fine control
  33811. // for small values and reasonable range.
  33812. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33813. density *= 0.5;
  33814. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33815. if (density < 0) {
  33816. density *= -1;
  33817. hue = (hue + 180) % 360;
  33818. }
  33819. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33820. result.scaleToRef(2, result);
  33821. result.a = 1 + 0.01 * saturation;
  33822. };
  33823. /**
  33824. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33825. * @param value The input slider value in range [-100,100].
  33826. * @returns Adjusted value.
  33827. */
  33828. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33829. value /= 100;
  33830. var x = Math.abs(value);
  33831. x = Math.pow(x, 2);
  33832. if (value < 0) {
  33833. x *= -1;
  33834. }
  33835. x *= 100;
  33836. return x;
  33837. };
  33838. /**
  33839. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33840. * @param hue The hue (H) input.
  33841. * @param saturation The saturation (S) input.
  33842. * @param brightness The brightness (B) input.
  33843. * @result An RGBA color represented as Vector4.
  33844. */
  33845. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33846. var h = ColorCurves.clamp(hue, 0, 360);
  33847. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33848. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33849. if (s === 0) {
  33850. result.r = v;
  33851. result.g = v;
  33852. result.b = v;
  33853. }
  33854. else {
  33855. // sector 0 to 5
  33856. h /= 60;
  33857. var i = Math.floor(h);
  33858. // fractional part of h
  33859. var f = h - i;
  33860. var p = v * (1 - s);
  33861. var q = v * (1 - s * f);
  33862. var t = v * (1 - s * (1 - f));
  33863. switch (i) {
  33864. case 0:
  33865. result.r = v;
  33866. result.g = t;
  33867. result.b = p;
  33868. break;
  33869. case 1:
  33870. result.r = q;
  33871. result.g = v;
  33872. result.b = p;
  33873. break;
  33874. case 2:
  33875. result.r = p;
  33876. result.g = v;
  33877. result.b = t;
  33878. break;
  33879. case 3:
  33880. result.r = p;
  33881. result.g = q;
  33882. result.b = v;
  33883. break;
  33884. case 4:
  33885. result.r = t;
  33886. result.g = p;
  33887. result.b = v;
  33888. break;
  33889. default:// case 5:
  33890. result.r = v;
  33891. result.g = p;
  33892. result.b = q;
  33893. break;
  33894. }
  33895. }
  33896. result.a = 1;
  33897. };
  33898. /**
  33899. * Returns a value clamped between min and max
  33900. * @param value The value to clamp
  33901. * @param min The minimum of value
  33902. * @param max The maximum of value
  33903. * @returns The clamped value.
  33904. */
  33905. ColorCurves.clamp = function (value, min, max) {
  33906. return Math.min(Math.max(value, min), max);
  33907. };
  33908. /**
  33909. * Clones the current color curve instance.
  33910. * @return The cloned curves
  33911. */
  33912. ColorCurves.prototype.clone = function () {
  33913. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33914. };
  33915. /**
  33916. * Serializes the current color curve instance to a json representation.
  33917. * @return a JSON representation
  33918. */
  33919. ColorCurves.prototype.serialize = function () {
  33920. return BABYLON.SerializationHelper.Serialize(this);
  33921. };
  33922. /**
  33923. * Parses the color curve from a json representation.
  33924. * @param source the JSON source to parse
  33925. * @return The parsed curves
  33926. */
  33927. ColorCurves.Parse = function (source) {
  33928. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33929. };
  33930. __decorate([
  33931. BABYLON.serialize()
  33932. ], ColorCurves.prototype, "_globalHue", void 0);
  33933. __decorate([
  33934. BABYLON.serialize()
  33935. ], ColorCurves.prototype, "_globalDensity", void 0);
  33936. __decorate([
  33937. BABYLON.serialize()
  33938. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33939. __decorate([
  33940. BABYLON.serialize()
  33941. ], ColorCurves.prototype, "_globalExposure", void 0);
  33942. __decorate([
  33943. BABYLON.serialize()
  33944. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33945. __decorate([
  33946. BABYLON.serialize()
  33947. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33948. __decorate([
  33949. BABYLON.serialize()
  33950. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33951. __decorate([
  33952. BABYLON.serialize()
  33953. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33954. __decorate([
  33955. BABYLON.serialize()
  33956. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33957. __decorate([
  33958. BABYLON.serialize()
  33959. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33960. __decorate([
  33961. BABYLON.serialize()
  33962. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33963. __decorate([
  33964. BABYLON.serialize()
  33965. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33966. return ColorCurves;
  33967. }());
  33968. BABYLON.ColorCurves = ColorCurves;
  33969. })(BABYLON || (BABYLON = {}));
  33970. //# sourceMappingURL=babylon.colorCurves.js.map
  33971. var BABYLON;
  33972. (function (BABYLON) {
  33973. var StandardMaterialDefines = /** @class */ (function (_super) {
  33974. __extends(StandardMaterialDefines, _super);
  33975. function StandardMaterialDefines() {
  33976. var _this = _super.call(this) || this;
  33977. _this.MAINUV1 = false;
  33978. _this.MAINUV2 = false;
  33979. _this.DIFFUSE = false;
  33980. _this.DIFFUSEDIRECTUV = 0;
  33981. _this.AMBIENT = false;
  33982. _this.AMBIENTDIRECTUV = 0;
  33983. _this.OPACITY = false;
  33984. _this.OPACITYDIRECTUV = 0;
  33985. _this.OPACITYRGB = false;
  33986. _this.REFLECTION = false;
  33987. _this.EMISSIVE = false;
  33988. _this.EMISSIVEDIRECTUV = 0;
  33989. _this.SPECULAR = false;
  33990. _this.SPECULARDIRECTUV = 0;
  33991. _this.BUMP = false;
  33992. _this.BUMPDIRECTUV = 0;
  33993. _this.PARALLAX = false;
  33994. _this.PARALLAXOCCLUSION = false;
  33995. _this.SPECULAROVERALPHA = false;
  33996. _this.CLIPPLANE = false;
  33997. _this.ALPHATEST = false;
  33998. _this.DEPTHPREPASS = false;
  33999. _this.ALPHAFROMDIFFUSE = false;
  34000. _this.POINTSIZE = false;
  34001. _this.FOG = false;
  34002. _this.SPECULARTERM = false;
  34003. _this.DIFFUSEFRESNEL = false;
  34004. _this.OPACITYFRESNEL = false;
  34005. _this.REFLECTIONFRESNEL = false;
  34006. _this.REFRACTIONFRESNEL = false;
  34007. _this.EMISSIVEFRESNEL = false;
  34008. _this.FRESNEL = false;
  34009. _this.NORMAL = false;
  34010. _this.UV1 = false;
  34011. _this.UV2 = false;
  34012. _this.VERTEXCOLOR = false;
  34013. _this.VERTEXALPHA = false;
  34014. _this.NUM_BONE_INFLUENCERS = 0;
  34015. _this.BonesPerMesh = 0;
  34016. _this.INSTANCES = false;
  34017. _this.GLOSSINESS = false;
  34018. _this.ROUGHNESS = false;
  34019. _this.EMISSIVEASILLUMINATION = false;
  34020. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34021. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34022. _this.LIGHTMAP = false;
  34023. _this.LIGHTMAPDIRECTUV = 0;
  34024. _this.USELIGHTMAPASSHADOWMAP = false;
  34025. _this.REFLECTIONMAP_3D = false;
  34026. _this.REFLECTIONMAP_SPHERICAL = false;
  34027. _this.REFLECTIONMAP_PLANAR = false;
  34028. _this.REFLECTIONMAP_CUBIC = false;
  34029. _this.REFLECTIONMAP_PROJECTION = false;
  34030. _this.REFLECTIONMAP_SKYBOX = false;
  34031. _this.REFLECTIONMAP_EXPLICIT = false;
  34032. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34033. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34034. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34035. _this.INVERTCUBICMAP = false;
  34036. _this.LOGARITHMICDEPTH = false;
  34037. _this.REFRACTION = false;
  34038. _this.REFRACTIONMAP_3D = false;
  34039. _this.REFLECTIONOVERALPHA = false;
  34040. _this.TWOSIDEDLIGHTING = false;
  34041. _this.SHADOWFLOAT = false;
  34042. _this.MORPHTARGETS = false;
  34043. _this.MORPHTARGETS_NORMAL = false;
  34044. _this.MORPHTARGETS_TANGENT = false;
  34045. _this.NUM_MORPH_INFLUENCERS = 0;
  34046. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34047. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34048. _this.IMAGEPROCESSING = false;
  34049. _this.VIGNETTE = false;
  34050. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34051. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34052. _this.TONEMAPPING = false;
  34053. _this.CONTRAST = false;
  34054. _this.COLORCURVES = false;
  34055. _this.COLORGRADING = false;
  34056. _this.COLORGRADING3D = false;
  34057. _this.SAMPLER3DGREENDEPTH = false;
  34058. _this.SAMPLER3DBGRMAP = false;
  34059. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34060. _this.EXPOSURE = false;
  34061. _this.rebuild();
  34062. return _this;
  34063. }
  34064. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34065. var modes = [
  34066. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34067. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34068. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34069. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34070. ];
  34071. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34072. var mode = modes_1[_i];
  34073. this[mode] = (mode === modeToEnable);
  34074. }
  34075. };
  34076. return StandardMaterialDefines;
  34077. }(BABYLON.MaterialDefines));
  34078. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34079. var StandardMaterial = /** @class */ (function (_super) {
  34080. __extends(StandardMaterial, _super);
  34081. function StandardMaterial(name, scene) {
  34082. var _this = _super.call(this, name, scene) || this;
  34083. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34084. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34085. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34086. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34087. _this.specularPower = 64;
  34088. _this._useAlphaFromDiffuseTexture = false;
  34089. _this._useEmissiveAsIllumination = false;
  34090. _this._linkEmissiveWithDiffuse = false;
  34091. _this._useSpecularOverAlpha = false;
  34092. _this._useReflectionOverAlpha = false;
  34093. _this._disableLighting = false;
  34094. _this._useParallax = false;
  34095. _this._useParallaxOcclusion = false;
  34096. _this.parallaxScaleBias = 0.05;
  34097. _this._roughness = 0;
  34098. _this.indexOfRefraction = 0.98;
  34099. _this.invertRefractionY = true;
  34100. _this._useLightmapAsShadowmap = false;
  34101. _this._useReflectionFresnelFromSpecular = false;
  34102. _this._useGlossinessFromSpecularMapAlpha = false;
  34103. _this._maxSimultaneousLights = 4;
  34104. /**
  34105. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34106. */
  34107. _this._invertNormalMapX = false;
  34108. /**
  34109. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34110. */
  34111. _this._invertNormalMapY = false;
  34112. /**
  34113. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34114. */
  34115. _this._twoSidedLighting = false;
  34116. _this._renderTargets = new BABYLON.SmartArray(16);
  34117. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34118. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34119. // Setup the default processing configuration to the scene.
  34120. _this._attachImageProcessingConfiguration(null);
  34121. _this.getRenderTargetTextures = function () {
  34122. _this._renderTargets.reset();
  34123. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34124. _this._renderTargets.push(_this._reflectionTexture);
  34125. }
  34126. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34127. _this._renderTargets.push(_this._refractionTexture);
  34128. }
  34129. return _this._renderTargets;
  34130. };
  34131. return _this;
  34132. }
  34133. ;
  34134. ;
  34135. ;
  34136. ;
  34137. ;
  34138. ;
  34139. ;
  34140. ;
  34141. ;
  34142. ;
  34143. ;
  34144. ;
  34145. ;
  34146. ;
  34147. ;
  34148. ;
  34149. ;
  34150. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34151. /**
  34152. * Gets the image processing configuration used either in this material.
  34153. */
  34154. get: function () {
  34155. return this._imageProcessingConfiguration;
  34156. },
  34157. /**
  34158. * Sets the Default image processing configuration used either in the this material.
  34159. *
  34160. * If sets to null, the scene one is in use.
  34161. */
  34162. set: function (value) {
  34163. this._attachImageProcessingConfiguration(value);
  34164. // Ensure the effect will be rebuilt.
  34165. this._markAllSubMeshesAsTexturesDirty();
  34166. },
  34167. enumerable: true,
  34168. configurable: true
  34169. });
  34170. /**
  34171. * Attaches a new image processing configuration to the Standard Material.
  34172. * @param configuration
  34173. */
  34174. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34175. var _this = this;
  34176. if (configuration === this._imageProcessingConfiguration) {
  34177. return;
  34178. }
  34179. // Detaches observer.
  34180. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34181. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34182. }
  34183. // Pick the scene configuration if needed.
  34184. if (!configuration) {
  34185. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34186. }
  34187. else {
  34188. this._imageProcessingConfiguration = configuration;
  34189. }
  34190. // Attaches observer.
  34191. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34192. _this._markAllSubMeshesAsImageProcessingDirty();
  34193. });
  34194. };
  34195. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34196. /**
  34197. * Gets wether the color curves effect is enabled.
  34198. */
  34199. get: function () {
  34200. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34201. },
  34202. /**
  34203. * Sets wether the color curves effect is enabled.
  34204. */
  34205. set: function (value) {
  34206. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34212. /**
  34213. * Gets wether the color grading effect is enabled.
  34214. */
  34215. get: function () {
  34216. return this.imageProcessingConfiguration.colorGradingEnabled;
  34217. },
  34218. /**
  34219. * Gets wether the color grading effect is enabled.
  34220. */
  34221. set: function (value) {
  34222. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34223. },
  34224. enumerable: true,
  34225. configurable: true
  34226. });
  34227. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34228. /**
  34229. * Gets wether tonemapping is enabled or not.
  34230. */
  34231. get: function () {
  34232. return this._imageProcessingConfiguration.toneMappingEnabled;
  34233. },
  34234. /**
  34235. * Sets wether tonemapping is enabled or not
  34236. */
  34237. set: function (value) {
  34238. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34239. },
  34240. enumerable: true,
  34241. configurable: true
  34242. });
  34243. ;
  34244. ;
  34245. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34246. /**
  34247. * The camera exposure used on this material.
  34248. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34249. * This corresponds to a photographic exposure.
  34250. */
  34251. get: function () {
  34252. return this._imageProcessingConfiguration.exposure;
  34253. },
  34254. /**
  34255. * The camera exposure used on this material.
  34256. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34257. * This corresponds to a photographic exposure.
  34258. */
  34259. set: function (value) {
  34260. this._imageProcessingConfiguration.exposure = value;
  34261. },
  34262. enumerable: true,
  34263. configurable: true
  34264. });
  34265. ;
  34266. ;
  34267. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34268. /**
  34269. * Gets The camera contrast used on this material.
  34270. */
  34271. get: function () {
  34272. return this._imageProcessingConfiguration.contrast;
  34273. },
  34274. /**
  34275. * Sets The camera contrast used on this material.
  34276. */
  34277. set: function (value) {
  34278. this._imageProcessingConfiguration.contrast = value;
  34279. },
  34280. enumerable: true,
  34281. configurable: true
  34282. });
  34283. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34284. /**
  34285. * Gets the Color Grading 2D Lookup Texture.
  34286. */
  34287. get: function () {
  34288. return this._imageProcessingConfiguration.colorGradingTexture;
  34289. },
  34290. /**
  34291. * Sets the Color Grading 2D Lookup Texture.
  34292. */
  34293. set: function (value) {
  34294. this._imageProcessingConfiguration.colorGradingTexture = value;
  34295. },
  34296. enumerable: true,
  34297. configurable: true
  34298. });
  34299. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34300. /**
  34301. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34302. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34303. * 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;
  34304. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34305. */
  34306. get: function () {
  34307. return this._imageProcessingConfiguration.colorCurves;
  34308. },
  34309. /**
  34310. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34311. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34312. * 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;
  34313. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34314. */
  34315. set: function (value) {
  34316. this._imageProcessingConfiguration.colorCurves = value;
  34317. },
  34318. enumerable: true,
  34319. configurable: true
  34320. });
  34321. StandardMaterial.prototype.getClassName = function () {
  34322. return "StandardMaterial";
  34323. };
  34324. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34325. get: function () {
  34326. return this._useLogarithmicDepth;
  34327. },
  34328. set: function (value) {
  34329. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34330. this._markAllSubMeshesAsMiscDirty();
  34331. },
  34332. enumerable: true,
  34333. configurable: true
  34334. });
  34335. StandardMaterial.prototype.needAlphaBlending = function () {
  34336. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34337. };
  34338. StandardMaterial.prototype.needAlphaTesting = function () {
  34339. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34340. };
  34341. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34342. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34343. };
  34344. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34345. return this._diffuseTexture;
  34346. };
  34347. /**
  34348. * Child classes can use it to update shaders
  34349. */
  34350. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34351. if (useInstances === void 0) { useInstances = false; }
  34352. if (subMesh.effect && this.isFrozen) {
  34353. if (this._wasPreviouslyReady && subMesh.effect) {
  34354. return true;
  34355. }
  34356. }
  34357. if (!subMesh._materialDefines) {
  34358. subMesh._materialDefines = new StandardMaterialDefines();
  34359. }
  34360. var scene = this.getScene();
  34361. var defines = subMesh._materialDefines;
  34362. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34363. if (defines._renderId === scene.getRenderId()) {
  34364. return true;
  34365. }
  34366. }
  34367. var engine = scene.getEngine();
  34368. // Lights
  34369. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34370. // Textures
  34371. if (defines._areTexturesDirty) {
  34372. defines._needUVs = false;
  34373. defines.MAINUV1 = false;
  34374. defines.MAINUV2 = false;
  34375. if (scene.texturesEnabled) {
  34376. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34377. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34378. return false;
  34379. }
  34380. else {
  34381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34382. }
  34383. }
  34384. else {
  34385. defines.DIFFUSE = false;
  34386. }
  34387. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34388. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34389. return false;
  34390. }
  34391. else {
  34392. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34393. }
  34394. }
  34395. else {
  34396. defines.AMBIENT = false;
  34397. }
  34398. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34399. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34400. return false;
  34401. }
  34402. else {
  34403. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34404. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34405. }
  34406. }
  34407. else {
  34408. defines.OPACITY = false;
  34409. }
  34410. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34411. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34412. return false;
  34413. }
  34414. else {
  34415. defines._needNormals = true;
  34416. defines.REFLECTION = true;
  34417. defines.ROUGHNESS = (this._roughness > 0);
  34418. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34419. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34420. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34421. switch (this._reflectionTexture.coordinatesMode) {
  34422. case BABYLON.Texture.CUBIC_MODE:
  34423. case BABYLON.Texture.INVCUBIC_MODE:
  34424. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34425. break;
  34426. case BABYLON.Texture.EXPLICIT_MODE:
  34427. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34428. break;
  34429. case BABYLON.Texture.PLANAR_MODE:
  34430. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34431. break;
  34432. case BABYLON.Texture.PROJECTION_MODE:
  34433. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34434. break;
  34435. case BABYLON.Texture.SKYBOX_MODE:
  34436. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34437. break;
  34438. case BABYLON.Texture.SPHERICAL_MODE:
  34439. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34440. break;
  34441. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34442. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34443. break;
  34444. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34445. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34446. break;
  34447. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34448. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34449. break;
  34450. }
  34451. }
  34452. }
  34453. else {
  34454. defines.REFLECTION = false;
  34455. }
  34456. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34457. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34458. return false;
  34459. }
  34460. else {
  34461. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34462. }
  34463. }
  34464. else {
  34465. defines.EMISSIVE = false;
  34466. }
  34467. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34468. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34469. return false;
  34470. }
  34471. else {
  34472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34473. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34474. }
  34475. }
  34476. else {
  34477. defines.LIGHTMAP = false;
  34478. }
  34479. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34480. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34481. return false;
  34482. }
  34483. else {
  34484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34485. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34486. }
  34487. }
  34488. else {
  34489. defines.SPECULAR = false;
  34490. }
  34491. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34492. // Bump texure can not be not blocking.
  34493. if (!this._bumpTexture.isReady()) {
  34494. return false;
  34495. }
  34496. else {
  34497. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34498. defines.PARALLAX = this._useParallax;
  34499. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34500. }
  34501. }
  34502. else {
  34503. defines.BUMP = false;
  34504. }
  34505. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34506. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34507. return false;
  34508. }
  34509. else {
  34510. defines._needUVs = true;
  34511. defines.REFRACTION = true;
  34512. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34513. }
  34514. }
  34515. else {
  34516. defines.REFRACTION = false;
  34517. }
  34518. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34519. }
  34520. else {
  34521. defines.DIFFUSE = false;
  34522. defines.AMBIENT = false;
  34523. defines.OPACITY = false;
  34524. defines.REFLECTION = false;
  34525. defines.EMISSIVE = false;
  34526. defines.LIGHTMAP = false;
  34527. defines.BUMP = false;
  34528. defines.REFRACTION = false;
  34529. }
  34530. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34531. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34532. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34533. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34534. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34535. }
  34536. if (defines._areImageProcessingDirty) {
  34537. if (!this._imageProcessingConfiguration.isReady()) {
  34538. return false;
  34539. }
  34540. this._imageProcessingConfiguration.prepareDefines(defines);
  34541. }
  34542. if (defines._areFresnelDirty) {
  34543. if (StandardMaterial.FresnelEnabled) {
  34544. // Fresnel
  34545. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34546. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34547. this._reflectionFresnelParameters) {
  34548. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34549. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34550. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34551. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34552. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34553. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34554. defines._needNormals = true;
  34555. defines.FRESNEL = true;
  34556. }
  34557. }
  34558. else {
  34559. defines.FRESNEL = false;
  34560. }
  34561. }
  34562. // Misc.
  34563. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34564. // Attribs
  34565. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34566. // Values that need to be evaluated on every frame
  34567. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34568. // Get correct effect
  34569. if (defines.isDirty) {
  34570. defines.markAsProcessed();
  34571. scene.resetCachedMaterial();
  34572. // Fallbacks
  34573. var fallbacks = new BABYLON.EffectFallbacks();
  34574. if (defines.REFLECTION) {
  34575. fallbacks.addFallback(0, "REFLECTION");
  34576. }
  34577. if (defines.SPECULAR) {
  34578. fallbacks.addFallback(0, "SPECULAR");
  34579. }
  34580. if (defines.BUMP) {
  34581. fallbacks.addFallback(0, "BUMP");
  34582. }
  34583. if (defines.PARALLAX) {
  34584. fallbacks.addFallback(1, "PARALLAX");
  34585. }
  34586. if (defines.PARALLAXOCCLUSION) {
  34587. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34588. }
  34589. if (defines.SPECULAROVERALPHA) {
  34590. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34591. }
  34592. if (defines.FOG) {
  34593. fallbacks.addFallback(1, "FOG");
  34594. }
  34595. if (defines.POINTSIZE) {
  34596. fallbacks.addFallback(0, "POINTSIZE");
  34597. }
  34598. if (defines.LOGARITHMICDEPTH) {
  34599. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34600. }
  34601. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34602. if (defines.SPECULARTERM) {
  34603. fallbacks.addFallback(0, "SPECULARTERM");
  34604. }
  34605. if (defines.DIFFUSEFRESNEL) {
  34606. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34607. }
  34608. if (defines.OPACITYFRESNEL) {
  34609. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34610. }
  34611. if (defines.REFLECTIONFRESNEL) {
  34612. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34613. }
  34614. if (defines.EMISSIVEFRESNEL) {
  34615. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34616. }
  34617. if (defines.FRESNEL) {
  34618. fallbacks.addFallback(4, "FRESNEL");
  34619. }
  34620. //Attributes
  34621. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34622. if (defines.NORMAL) {
  34623. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34624. }
  34625. if (defines.UV1) {
  34626. attribs.push(BABYLON.VertexBuffer.UVKind);
  34627. }
  34628. if (defines.UV2) {
  34629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34630. }
  34631. if (defines.VERTEXCOLOR) {
  34632. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34633. }
  34634. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34635. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34636. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34637. var shaderName = "default";
  34638. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34639. "vFogInfos", "vFogColor", "pointSize",
  34640. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34641. "mBones",
  34642. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34643. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34644. "logarithmicDepthConstant", "vTangentSpaceParams"
  34645. ];
  34646. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34647. var uniformBuffers = ["Material", "Scene"];
  34648. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34649. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34650. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34651. uniformsNames: uniforms,
  34652. uniformBuffersNames: uniformBuffers,
  34653. samplers: samplers,
  34654. defines: defines,
  34655. maxSimultaneousLights: this._maxSimultaneousLights
  34656. });
  34657. if (this.customShaderNameResolve) {
  34658. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34659. }
  34660. var join = defines.toString();
  34661. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34662. attributes: attribs,
  34663. uniformsNames: uniforms,
  34664. uniformBuffersNames: uniformBuffers,
  34665. samplers: samplers,
  34666. defines: join,
  34667. fallbacks: fallbacks,
  34668. onCompiled: this.onCompiled,
  34669. onError: this.onError,
  34670. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34671. }, engine), defines);
  34672. this.buildUniformLayout();
  34673. }
  34674. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34675. return false;
  34676. }
  34677. defines._renderId = scene.getRenderId();
  34678. this._wasPreviouslyReady = true;
  34679. return true;
  34680. };
  34681. StandardMaterial.prototype.buildUniformLayout = function () {
  34682. // Order is important !
  34683. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34684. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34685. this._uniformBuffer.addUniform("opacityParts", 4);
  34686. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34687. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34688. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34689. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34690. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34691. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34692. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34693. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34694. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34695. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34696. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34697. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34698. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34699. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34700. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34701. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34702. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34703. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34704. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34705. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34706. this._uniformBuffer.addUniform("specularMatrix", 16);
  34707. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34708. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34709. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34710. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34711. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34712. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34713. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34714. this._uniformBuffer.addUniform("pointSize", 1);
  34715. this._uniformBuffer.create();
  34716. };
  34717. StandardMaterial.prototype.unbind = function () {
  34718. if (this._activeEffect) {
  34719. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34720. this._activeEffect.setTexture("reflection2DSampler", null);
  34721. }
  34722. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34723. this._activeEffect.setTexture("refraction2DSampler", null);
  34724. }
  34725. }
  34726. _super.prototype.unbind.call(this);
  34727. };
  34728. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34729. var scene = this.getScene();
  34730. var defines = subMesh._materialDefines;
  34731. if (!defines) {
  34732. return;
  34733. }
  34734. var effect = subMesh.effect;
  34735. if (!effect) {
  34736. return;
  34737. }
  34738. this._activeEffect = effect;
  34739. // Matrices
  34740. this.bindOnlyWorldMatrix(world);
  34741. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34742. // Bones
  34743. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34744. if (mustRebind) {
  34745. this._uniformBuffer.bindToEffect(effect, "Material");
  34746. this.bindViewProjection(effect);
  34747. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34748. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34749. // Fresnel
  34750. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34751. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34752. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34753. }
  34754. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34755. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34756. }
  34757. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34758. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34759. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34760. }
  34761. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34762. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34763. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34764. }
  34765. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34766. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34767. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34768. }
  34769. }
  34770. // Textures
  34771. if (scene.texturesEnabled) {
  34772. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34773. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34774. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34775. }
  34776. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34777. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34778. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34779. }
  34780. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34781. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34782. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34783. }
  34784. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34785. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34786. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34787. }
  34788. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34789. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34790. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34791. }
  34792. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34793. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34794. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34795. }
  34796. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34797. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34798. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34799. }
  34800. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34801. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34802. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34803. if (scene._mirroredCameraPosition) {
  34804. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34805. }
  34806. else {
  34807. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34808. }
  34809. }
  34810. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34811. var depth = 1.0;
  34812. if (!this._refractionTexture.isCube) {
  34813. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34814. if (this._refractionTexture.depth) {
  34815. depth = this._refractionTexture.depth;
  34816. }
  34817. }
  34818. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34819. }
  34820. }
  34821. // Point size
  34822. if (this.pointsCloud) {
  34823. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34824. }
  34825. if (defines.SPECULARTERM) {
  34826. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34827. }
  34828. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34829. // Diffuse
  34830. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34831. }
  34832. // Textures
  34833. if (scene.texturesEnabled) {
  34834. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34835. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34836. }
  34837. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34838. effect.setTexture("ambientSampler", this._ambientTexture);
  34839. }
  34840. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34841. effect.setTexture("opacitySampler", this._opacityTexture);
  34842. }
  34843. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34844. if (this._reflectionTexture.isCube) {
  34845. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34846. }
  34847. else {
  34848. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34849. }
  34850. }
  34851. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34852. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34853. }
  34854. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34855. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34856. }
  34857. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34858. effect.setTexture("specularSampler", this._specularTexture);
  34859. }
  34860. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34861. effect.setTexture("bumpSampler", this._bumpTexture);
  34862. }
  34863. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34864. var depth = 1.0;
  34865. if (this._refractionTexture.isCube) {
  34866. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34867. }
  34868. else {
  34869. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34870. }
  34871. }
  34872. }
  34873. // Clip plane
  34874. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34875. // Colors
  34876. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34877. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34878. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34879. }
  34880. if (mustRebind || !this.isFrozen) {
  34881. // Lights
  34882. if (scene.lightsEnabled && !this._disableLighting) {
  34883. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34884. }
  34885. // View
  34886. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34887. this.bindView(effect);
  34888. }
  34889. // Fog
  34890. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34891. // Morph targets
  34892. if (defines.NUM_MORPH_INFLUENCERS) {
  34893. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34894. }
  34895. // Log. depth
  34896. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34897. // image processing
  34898. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  34899. this._imageProcessingConfiguration.bind(this._activeEffect);
  34900. }
  34901. }
  34902. this._uniformBuffer.update();
  34903. this._afterBind(mesh, this._activeEffect);
  34904. };
  34905. StandardMaterial.prototype.getAnimatables = function () {
  34906. var results = [];
  34907. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34908. results.push(this._diffuseTexture);
  34909. }
  34910. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34911. results.push(this._ambientTexture);
  34912. }
  34913. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34914. results.push(this._opacityTexture);
  34915. }
  34916. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34917. results.push(this._reflectionTexture);
  34918. }
  34919. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34920. results.push(this._emissiveTexture);
  34921. }
  34922. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34923. results.push(this._specularTexture);
  34924. }
  34925. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34926. results.push(this._bumpTexture);
  34927. }
  34928. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34929. results.push(this._lightmapTexture);
  34930. }
  34931. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34932. results.push(this._refractionTexture);
  34933. }
  34934. return results;
  34935. };
  34936. StandardMaterial.prototype.getActiveTextures = function () {
  34937. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34938. if (this._diffuseTexture) {
  34939. activeTextures.push(this._diffuseTexture);
  34940. }
  34941. if (this._ambientTexture) {
  34942. activeTextures.push(this._ambientTexture);
  34943. }
  34944. if (this._opacityTexture) {
  34945. activeTextures.push(this._opacityTexture);
  34946. }
  34947. if (this._reflectionTexture) {
  34948. activeTextures.push(this._reflectionTexture);
  34949. }
  34950. if (this._emissiveTexture) {
  34951. activeTextures.push(this._emissiveTexture);
  34952. }
  34953. if (this._specularTexture) {
  34954. activeTextures.push(this._specularTexture);
  34955. }
  34956. if (this._bumpTexture) {
  34957. activeTextures.push(this._bumpTexture);
  34958. }
  34959. if (this._lightmapTexture) {
  34960. activeTextures.push(this._lightmapTexture);
  34961. }
  34962. if (this._refractionTexture) {
  34963. activeTextures.push(this._refractionTexture);
  34964. }
  34965. return activeTextures;
  34966. };
  34967. StandardMaterial.prototype.hasTexture = function (texture) {
  34968. if (_super.prototype.hasTexture.call(this, texture)) {
  34969. return true;
  34970. }
  34971. if (this._diffuseTexture === texture) {
  34972. return true;
  34973. }
  34974. if (this._ambientTexture === texture) {
  34975. return true;
  34976. }
  34977. if (this._opacityTexture === texture) {
  34978. return true;
  34979. }
  34980. if (this._reflectionTexture === texture) {
  34981. return true;
  34982. }
  34983. if (this._emissiveTexture === texture) {
  34984. return true;
  34985. }
  34986. if (this._specularTexture === texture) {
  34987. return true;
  34988. }
  34989. if (this._bumpTexture === texture) {
  34990. return true;
  34991. }
  34992. if (this._lightmapTexture === texture) {
  34993. return true;
  34994. }
  34995. if (this._refractionTexture === texture) {
  34996. return true;
  34997. }
  34998. return false;
  34999. };
  35000. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35001. if (forceDisposeTextures) {
  35002. if (this._diffuseTexture) {
  35003. this._diffuseTexture.dispose();
  35004. }
  35005. if (this._ambientTexture) {
  35006. this._ambientTexture.dispose();
  35007. }
  35008. if (this._opacityTexture) {
  35009. this._opacityTexture.dispose();
  35010. }
  35011. if (this._reflectionTexture) {
  35012. this._reflectionTexture.dispose();
  35013. }
  35014. if (this._emissiveTexture) {
  35015. this._emissiveTexture.dispose();
  35016. }
  35017. if (this._specularTexture) {
  35018. this._specularTexture.dispose();
  35019. }
  35020. if (this._bumpTexture) {
  35021. this._bumpTexture.dispose();
  35022. }
  35023. if (this._lightmapTexture) {
  35024. this._lightmapTexture.dispose();
  35025. }
  35026. if (this._refractionTexture) {
  35027. this._refractionTexture.dispose();
  35028. }
  35029. }
  35030. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35031. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35032. }
  35033. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35034. };
  35035. StandardMaterial.prototype.clone = function (name) {
  35036. var _this = this;
  35037. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35038. result.name = name;
  35039. result.id = name;
  35040. return result;
  35041. };
  35042. StandardMaterial.prototype.serialize = function () {
  35043. return BABYLON.SerializationHelper.Serialize(this);
  35044. };
  35045. // Statics
  35046. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35047. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35048. };
  35049. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35050. get: function () {
  35051. return StandardMaterial._DiffuseTextureEnabled;
  35052. },
  35053. set: function (value) {
  35054. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35055. return;
  35056. }
  35057. StandardMaterial._DiffuseTextureEnabled = value;
  35058. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35064. get: function () {
  35065. return StandardMaterial._AmbientTextureEnabled;
  35066. },
  35067. set: function (value) {
  35068. if (StandardMaterial._AmbientTextureEnabled === value) {
  35069. return;
  35070. }
  35071. StandardMaterial._AmbientTextureEnabled = value;
  35072. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35078. get: function () {
  35079. return StandardMaterial._OpacityTextureEnabled;
  35080. },
  35081. set: function (value) {
  35082. if (StandardMaterial._OpacityTextureEnabled === value) {
  35083. return;
  35084. }
  35085. StandardMaterial._OpacityTextureEnabled = value;
  35086. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35092. get: function () {
  35093. return StandardMaterial._ReflectionTextureEnabled;
  35094. },
  35095. set: function (value) {
  35096. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35097. return;
  35098. }
  35099. StandardMaterial._ReflectionTextureEnabled = value;
  35100. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35106. get: function () {
  35107. return StandardMaterial._EmissiveTextureEnabled;
  35108. },
  35109. set: function (value) {
  35110. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35111. return;
  35112. }
  35113. StandardMaterial._EmissiveTextureEnabled = value;
  35114. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35120. get: function () {
  35121. return StandardMaterial._SpecularTextureEnabled;
  35122. },
  35123. set: function (value) {
  35124. if (StandardMaterial._SpecularTextureEnabled === value) {
  35125. return;
  35126. }
  35127. StandardMaterial._SpecularTextureEnabled = value;
  35128. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35134. get: function () {
  35135. return StandardMaterial._BumpTextureEnabled;
  35136. },
  35137. set: function (value) {
  35138. if (StandardMaterial._BumpTextureEnabled === value) {
  35139. return;
  35140. }
  35141. StandardMaterial._BumpTextureEnabled = value;
  35142. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35148. get: function () {
  35149. return StandardMaterial._LightmapTextureEnabled;
  35150. },
  35151. set: function (value) {
  35152. if (StandardMaterial._LightmapTextureEnabled === value) {
  35153. return;
  35154. }
  35155. StandardMaterial._LightmapTextureEnabled = value;
  35156. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35162. get: function () {
  35163. return StandardMaterial._RefractionTextureEnabled;
  35164. },
  35165. set: function (value) {
  35166. if (StandardMaterial._RefractionTextureEnabled === value) {
  35167. return;
  35168. }
  35169. StandardMaterial._RefractionTextureEnabled = value;
  35170. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35176. get: function () {
  35177. return StandardMaterial._ColorGradingTextureEnabled;
  35178. },
  35179. set: function (value) {
  35180. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35181. return;
  35182. }
  35183. StandardMaterial._ColorGradingTextureEnabled = value;
  35184. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35190. get: function () {
  35191. return StandardMaterial._FresnelEnabled;
  35192. },
  35193. set: function (value) {
  35194. if (StandardMaterial._FresnelEnabled === value) {
  35195. return;
  35196. }
  35197. StandardMaterial._FresnelEnabled = value;
  35198. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. // Flags used to enable or disable a type of texture for all Standard Materials
  35204. StandardMaterial._DiffuseTextureEnabled = true;
  35205. StandardMaterial._AmbientTextureEnabled = true;
  35206. StandardMaterial._OpacityTextureEnabled = true;
  35207. StandardMaterial._ReflectionTextureEnabled = true;
  35208. StandardMaterial._EmissiveTextureEnabled = true;
  35209. StandardMaterial._SpecularTextureEnabled = true;
  35210. StandardMaterial._BumpTextureEnabled = true;
  35211. StandardMaterial._LightmapTextureEnabled = true;
  35212. StandardMaterial._RefractionTextureEnabled = true;
  35213. StandardMaterial._ColorGradingTextureEnabled = true;
  35214. StandardMaterial._FresnelEnabled = true;
  35215. __decorate([
  35216. BABYLON.serializeAsTexture("diffuseTexture")
  35217. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35218. __decorate([
  35219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35220. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35221. __decorate([
  35222. BABYLON.serializeAsTexture("ambientTexture")
  35223. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35224. __decorate([
  35225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35226. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35227. __decorate([
  35228. BABYLON.serializeAsTexture("opacityTexture")
  35229. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35230. __decorate([
  35231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35232. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35233. __decorate([
  35234. BABYLON.serializeAsTexture("reflectionTexture")
  35235. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35236. __decorate([
  35237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35238. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35239. __decorate([
  35240. BABYLON.serializeAsTexture("emissiveTexture")
  35241. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35242. __decorate([
  35243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35244. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35245. __decorate([
  35246. BABYLON.serializeAsTexture("specularTexture")
  35247. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35248. __decorate([
  35249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35250. ], StandardMaterial.prototype, "specularTexture", void 0);
  35251. __decorate([
  35252. BABYLON.serializeAsTexture("bumpTexture")
  35253. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35254. __decorate([
  35255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35256. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35257. __decorate([
  35258. BABYLON.serializeAsTexture("lightmapTexture")
  35259. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35260. __decorate([
  35261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35262. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35263. __decorate([
  35264. BABYLON.serializeAsTexture("refractionTexture")
  35265. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35266. __decorate([
  35267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35268. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35269. __decorate([
  35270. BABYLON.serializeAsColor3("ambient")
  35271. ], StandardMaterial.prototype, "ambientColor", void 0);
  35272. __decorate([
  35273. BABYLON.serializeAsColor3("diffuse")
  35274. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35275. __decorate([
  35276. BABYLON.serializeAsColor3("specular")
  35277. ], StandardMaterial.prototype, "specularColor", void 0);
  35278. __decorate([
  35279. BABYLON.serializeAsColor3("emissive")
  35280. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35281. __decorate([
  35282. BABYLON.serialize()
  35283. ], StandardMaterial.prototype, "specularPower", void 0);
  35284. __decorate([
  35285. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35286. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35287. __decorate([
  35288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35289. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35290. __decorate([
  35291. BABYLON.serialize("useEmissiveAsIllumination")
  35292. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35293. __decorate([
  35294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35295. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35296. __decorate([
  35297. BABYLON.serialize("linkEmissiveWithDiffuse")
  35298. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35299. __decorate([
  35300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35301. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35302. __decorate([
  35303. BABYLON.serialize("useSpecularOverAlpha")
  35304. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35305. __decorate([
  35306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35307. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35308. __decorate([
  35309. BABYLON.serialize("useReflectionOverAlpha")
  35310. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35311. __decorate([
  35312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35313. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35314. __decorate([
  35315. BABYLON.serialize("disableLighting")
  35316. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35317. __decorate([
  35318. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35319. ], StandardMaterial.prototype, "disableLighting", void 0);
  35320. __decorate([
  35321. BABYLON.serialize("useParallax")
  35322. ], StandardMaterial.prototype, "_useParallax", void 0);
  35323. __decorate([
  35324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35325. ], StandardMaterial.prototype, "useParallax", void 0);
  35326. __decorate([
  35327. BABYLON.serialize("useParallaxOcclusion")
  35328. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35329. __decorate([
  35330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35331. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35332. __decorate([
  35333. BABYLON.serialize()
  35334. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35335. __decorate([
  35336. BABYLON.serialize("roughness")
  35337. ], StandardMaterial.prototype, "_roughness", void 0);
  35338. __decorate([
  35339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35340. ], StandardMaterial.prototype, "roughness", void 0);
  35341. __decorate([
  35342. BABYLON.serialize()
  35343. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35344. __decorate([
  35345. BABYLON.serialize()
  35346. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35347. __decorate([
  35348. BABYLON.serialize("useLightmapAsShadowmap")
  35349. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35350. __decorate([
  35351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35352. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35353. __decorate([
  35354. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35355. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35356. __decorate([
  35357. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35358. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35359. __decorate([
  35360. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35361. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35362. __decorate([
  35363. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35364. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35365. __decorate([
  35366. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35367. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35368. __decorate([
  35369. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35370. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35371. __decorate([
  35372. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35373. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35374. __decorate([
  35375. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35376. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35377. __decorate([
  35378. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35379. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35380. __decorate([
  35381. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35382. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35383. __decorate([
  35384. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35385. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35386. __decorate([
  35387. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35388. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35389. __decorate([
  35390. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35391. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35392. __decorate([
  35393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35394. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35395. __decorate([
  35396. BABYLON.serialize("maxSimultaneousLights")
  35397. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35398. __decorate([
  35399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35400. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35401. __decorate([
  35402. BABYLON.serialize("invertNormalMapX")
  35403. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35404. __decorate([
  35405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35406. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35407. __decorate([
  35408. BABYLON.serialize("invertNormalMapY")
  35409. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35410. __decorate([
  35411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35412. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35413. __decorate([
  35414. BABYLON.serialize("twoSidedLighting")
  35415. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35416. __decorate([
  35417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35418. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35419. __decorate([
  35420. BABYLON.serialize()
  35421. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35422. return StandardMaterial;
  35423. }(BABYLON.PushMaterial));
  35424. BABYLON.StandardMaterial = StandardMaterial;
  35425. })(BABYLON || (BABYLON = {}));
  35426. //# sourceMappingURL=babylon.standardMaterial.js.map
  35427. var BABYLON;
  35428. (function (BABYLON) {
  35429. var PBRMaterialDefines = /** @class */ (function (_super) {
  35430. __extends(PBRMaterialDefines, _super);
  35431. function PBRMaterialDefines() {
  35432. var _this = _super.call(this) || this;
  35433. _this.PBR = true;
  35434. _this.MAINUV1 = false;
  35435. _this.MAINUV2 = false;
  35436. _this.UV1 = false;
  35437. _this.UV2 = false;
  35438. _this.ALBEDO = false;
  35439. _this.ALBEDODIRECTUV = 0;
  35440. _this.VERTEXCOLOR = false;
  35441. _this.AMBIENT = false;
  35442. _this.AMBIENTDIRECTUV = 0;
  35443. _this.AMBIENTINGRAYSCALE = false;
  35444. _this.OPACITY = false;
  35445. _this.VERTEXALPHA = false;
  35446. _this.OPACITYDIRECTUV = 0;
  35447. _this.OPACITYRGB = false;
  35448. _this.ALPHATEST = false;
  35449. _this.DEPTHPREPASS = false;
  35450. _this.ALPHABLEND = false;
  35451. _this.ALPHAFROMALBEDO = false;
  35452. _this.ALPHATESTVALUE = 0.5;
  35453. _this.SPECULAROVERALPHA = false;
  35454. _this.RADIANCEOVERALPHA = false;
  35455. _this.ALPHAFRESNEL = false;
  35456. _this.LINEARALPHAFRESNEL = false;
  35457. _this.PREMULTIPLYALPHA = false;
  35458. _this.EMISSIVE = false;
  35459. _this.EMISSIVEDIRECTUV = 0;
  35460. _this.REFLECTIVITY = false;
  35461. _this.REFLECTIVITYDIRECTUV = 0;
  35462. _this.SPECULARTERM = false;
  35463. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35464. _this.MICROSURFACEAUTOMATIC = false;
  35465. _this.LODBASEDMICROSFURACE = false;
  35466. _this.MICROSURFACEMAP = false;
  35467. _this.MICROSURFACEMAPDIRECTUV = 0;
  35468. _this.METALLICWORKFLOW = false;
  35469. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35470. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35471. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35472. _this.AOSTOREINMETALMAPRED = false;
  35473. _this.ENVIRONMENTBRDF = false;
  35474. _this.NORMAL = false;
  35475. _this.TANGENT = false;
  35476. _this.BUMP = false;
  35477. _this.BUMPDIRECTUV = 0;
  35478. _this.PARALLAX = false;
  35479. _this.PARALLAXOCCLUSION = false;
  35480. _this.NORMALXYSCALE = true;
  35481. _this.LIGHTMAP = false;
  35482. _this.LIGHTMAPDIRECTUV = 0;
  35483. _this.USELIGHTMAPASSHADOWMAP = false;
  35484. _this.REFLECTION = false;
  35485. _this.REFLECTIONMAP_3D = false;
  35486. _this.REFLECTIONMAP_SPHERICAL = false;
  35487. _this.REFLECTIONMAP_PLANAR = false;
  35488. _this.REFLECTIONMAP_CUBIC = false;
  35489. _this.REFLECTIONMAP_PROJECTION = false;
  35490. _this.REFLECTIONMAP_SKYBOX = false;
  35491. _this.REFLECTIONMAP_EXPLICIT = false;
  35492. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35493. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35494. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35495. _this.INVERTCUBICMAP = false;
  35496. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35497. _this.USESPHERICALINVERTEX = false;
  35498. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35499. _this.LODINREFLECTIONALPHA = false;
  35500. _this.GAMMAREFLECTION = false;
  35501. _this.RADIANCEOCCLUSION = false;
  35502. _this.HORIZONOCCLUSION = false;
  35503. _this.REFRACTION = false;
  35504. _this.REFRACTIONMAP_3D = false;
  35505. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35506. _this.LODINREFRACTIONALPHA = false;
  35507. _this.GAMMAREFRACTION = false;
  35508. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35509. _this.INSTANCES = false;
  35510. _this.NUM_BONE_INFLUENCERS = 0;
  35511. _this.BonesPerMesh = 0;
  35512. _this.NONUNIFORMSCALING = false;
  35513. _this.MORPHTARGETS = false;
  35514. _this.MORPHTARGETS_NORMAL = false;
  35515. _this.MORPHTARGETS_TANGENT = false;
  35516. _this.NUM_MORPH_INFLUENCERS = 0;
  35517. _this.IMAGEPROCESSING = false;
  35518. _this.VIGNETTE = false;
  35519. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35520. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35521. _this.TONEMAPPING = false;
  35522. _this.CONTRAST = false;
  35523. _this.COLORCURVES = false;
  35524. _this.COLORGRADING = false;
  35525. _this.COLORGRADING3D = false;
  35526. _this.SAMPLER3DGREENDEPTH = false;
  35527. _this.SAMPLER3DBGRMAP = false;
  35528. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35529. _this.EXPOSURE = false;
  35530. _this.USEPHYSICALLIGHTFALLOFF = false;
  35531. _this.TWOSIDEDLIGHTING = false;
  35532. _this.SHADOWFLOAT = false;
  35533. _this.CLIPPLANE = false;
  35534. _this.POINTSIZE = false;
  35535. _this.FOG = false;
  35536. _this.LOGARITHMICDEPTH = false;
  35537. _this.FORCENORMALFORWARD = false;
  35538. _this.rebuild();
  35539. return _this;
  35540. }
  35541. PBRMaterialDefines.prototype.reset = function () {
  35542. _super.prototype.reset.call(this);
  35543. this.ALPHATESTVALUE = 0.5;
  35544. this.PBR = true;
  35545. };
  35546. return PBRMaterialDefines;
  35547. }(BABYLON.MaterialDefines));
  35548. /**
  35549. * The Physically based material base class of BJS.
  35550. *
  35551. * This offers the main features of a standard PBR material.
  35552. * For more information, please refer to the documentation :
  35553. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35554. */
  35555. var PBRBaseMaterial = /** @class */ (function (_super) {
  35556. __extends(PBRBaseMaterial, _super);
  35557. /**
  35558. * Instantiates a new PBRMaterial instance.
  35559. *
  35560. * @param name The material name
  35561. * @param scene The scene the material will be use in.
  35562. */
  35563. function PBRBaseMaterial(name, scene) {
  35564. var _this = _super.call(this, name, scene) || this;
  35565. /**
  35566. * Intensity of the direct lights e.g. the four lights available in your scene.
  35567. * This impacts both the direct diffuse and specular highlights.
  35568. */
  35569. _this._directIntensity = 1.0;
  35570. /**
  35571. * Intensity of the emissive part of the material.
  35572. * This helps controlling the emissive effect without modifying the emissive color.
  35573. */
  35574. _this._emissiveIntensity = 1.0;
  35575. /**
  35576. * Intensity of the environment e.g. how much the environment will light the object
  35577. * either through harmonics for rough material or through the refelction for shiny ones.
  35578. */
  35579. _this._environmentIntensity = 1.0;
  35580. /**
  35581. * This is a special control allowing the reduction of the specular highlights coming from the
  35582. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35583. */
  35584. _this._specularIntensity = 1.0;
  35585. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35586. /**
  35587. * Debug Control allowing disabling the bump map on this material.
  35588. */
  35589. _this._disableBumpMap = false;
  35590. /**
  35591. * AKA Occlusion Texture Intensity in other nomenclature.
  35592. */
  35593. _this._ambientTextureStrength = 1.0;
  35594. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35595. /**
  35596. * AKA Diffuse Color in other nomenclature.
  35597. */
  35598. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35599. /**
  35600. * AKA Specular Color in other nomenclature.
  35601. */
  35602. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35603. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35604. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35605. /**
  35606. * AKA Glossiness in other nomenclature.
  35607. */
  35608. _this._microSurface = 0.9;
  35609. /**
  35610. * source material index of refraction (IOR)' / 'destination material IOR.
  35611. */
  35612. _this._indexOfRefraction = 0.66;
  35613. /**
  35614. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35615. */
  35616. _this._invertRefractionY = false;
  35617. /**
  35618. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35619. * Materials half opaque for instance using refraction could benefit from this control.
  35620. */
  35621. _this._linkRefractionWithTransparency = false;
  35622. _this._useLightmapAsShadowmap = false;
  35623. /**
  35624. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35625. * makes the reflect vector face the model (under horizon).
  35626. */
  35627. _this._useHorizonOcclusion = true;
  35628. /**
  35629. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35630. * too much the area relying on ambient texture to define their ambient occlusion.
  35631. */
  35632. _this._useRadianceOcclusion = true;
  35633. /**
  35634. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35635. */
  35636. _this._useAlphaFromAlbedoTexture = false;
  35637. /**
  35638. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35639. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35640. */
  35641. _this._useSpecularOverAlpha = true;
  35642. /**
  35643. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35644. */
  35645. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35646. /**
  35647. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35648. */
  35649. _this._useRoughnessFromMetallicTextureAlpha = true;
  35650. /**
  35651. * Specifies if the metallic texture contains the roughness information in its green channel.
  35652. */
  35653. _this._useRoughnessFromMetallicTextureGreen = false;
  35654. /**
  35655. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35656. */
  35657. _this._useMetallnessFromMetallicTextureBlue = false;
  35658. /**
  35659. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35660. */
  35661. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35662. /**
  35663. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35664. */
  35665. _this._useAmbientInGrayScale = false;
  35666. /**
  35667. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35668. * The material will try to infer what glossiness each pixel should be.
  35669. */
  35670. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35671. /**
  35672. * BJS is using an harcoded light falloff based on a manually sets up range.
  35673. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35674. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35675. */
  35676. _this._usePhysicalLightFalloff = true;
  35677. /**
  35678. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35679. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35680. */
  35681. _this._useRadianceOverAlpha = true;
  35682. /**
  35683. * Allows using the bump map in parallax mode.
  35684. */
  35685. _this._useParallax = false;
  35686. /**
  35687. * Allows using the bump map in parallax occlusion mode.
  35688. */
  35689. _this._useParallaxOcclusion = false;
  35690. /**
  35691. * Controls the scale bias of the parallax mode.
  35692. */
  35693. _this._parallaxScaleBias = 0.05;
  35694. /**
  35695. * If sets to true, disables all the lights affecting the material.
  35696. */
  35697. _this._disableLighting = false;
  35698. /**
  35699. * Number of Simultaneous lights allowed on the material.
  35700. */
  35701. _this._maxSimultaneousLights = 4;
  35702. /**
  35703. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35704. */
  35705. _this._invertNormalMapX = false;
  35706. /**
  35707. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35708. */
  35709. _this._invertNormalMapY = false;
  35710. /**
  35711. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35712. */
  35713. _this._twoSidedLighting = false;
  35714. /**
  35715. * Defines the alpha limits in alpha test mode.
  35716. */
  35717. _this._alphaCutOff = 0.4;
  35718. /**
  35719. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35720. */
  35721. _this._forceAlphaTest = false;
  35722. /**
  35723. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35724. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  35725. */
  35726. _this._useAlphaFresnel = false;
  35727. /**
  35728. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35729. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  35730. */
  35731. _this._useLinearAlphaFresnel = false;
  35732. /**
  35733. * The transparency mode of the material.
  35734. */
  35735. _this._transparencyMode = null;
  35736. /**
  35737. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35738. * from cos thetav and roughness:
  35739. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35740. */
  35741. _this._environmentBRDFTexture = null;
  35742. /**
  35743. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35744. */
  35745. _this._forceIrradianceInFragment = false;
  35746. /**
  35747. * Force normal to face away from face.
  35748. * (Temporary internal fix to remove before 3.1)
  35749. */
  35750. _this._forceNormalForward = false;
  35751. _this._renderTargets = new BABYLON.SmartArray(16);
  35752. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35753. // Setup the default processing configuration to the scene.
  35754. _this._attachImageProcessingConfiguration(null);
  35755. _this.getRenderTargetTextures = function () {
  35756. _this._renderTargets.reset();
  35757. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35758. _this._renderTargets.push(_this._reflectionTexture);
  35759. }
  35760. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35761. _this._renderTargets.push(_this._refractionTexture);
  35762. }
  35763. return _this._renderTargets;
  35764. };
  35765. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35766. return _this;
  35767. }
  35768. /**
  35769. * Attaches a new image processing configuration to the PBR Material.
  35770. * @param configuration
  35771. */
  35772. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35773. var _this = this;
  35774. if (configuration === this._imageProcessingConfiguration) {
  35775. return;
  35776. }
  35777. // Detaches observer.
  35778. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35779. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35780. }
  35781. // Pick the scene configuration if needed.
  35782. if (!configuration) {
  35783. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35784. }
  35785. else {
  35786. this._imageProcessingConfiguration = configuration;
  35787. }
  35788. // Attaches observer.
  35789. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35790. _this._markAllSubMeshesAsImageProcessingDirty();
  35791. });
  35792. };
  35793. PBRBaseMaterial.prototype.getClassName = function () {
  35794. return "PBRBaseMaterial";
  35795. };
  35796. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35797. get: function () {
  35798. return this._useLogarithmicDepth;
  35799. },
  35800. set: function (value) {
  35801. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35802. },
  35803. enumerable: true,
  35804. configurable: true
  35805. });
  35806. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35807. /**
  35808. * Gets the current transparency mode.
  35809. */
  35810. get: function () {
  35811. return this._transparencyMode;
  35812. },
  35813. /**
  35814. * Sets the transparency mode of the material.
  35815. */
  35816. set: function (value) {
  35817. if (this._transparencyMode === value) {
  35818. return;
  35819. }
  35820. this._transparencyMode = value;
  35821. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35822. this._markAllSubMeshesAsTexturesDirty();
  35823. },
  35824. enumerable: true,
  35825. configurable: true
  35826. });
  35827. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35828. /**
  35829. * Returns true if alpha blending should be disabled.
  35830. */
  35831. get: function () {
  35832. return (this._linkRefractionWithTransparency ||
  35833. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35834. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. /**
  35840. * Specifies whether or not this material should be rendered in alpha blend mode.
  35841. */
  35842. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35843. if (this._disableAlphaBlending) {
  35844. return false;
  35845. }
  35846. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35847. };
  35848. /**
  35849. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35850. */
  35851. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35852. if (this._disableAlphaBlending) {
  35853. return false;
  35854. }
  35855. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35856. };
  35857. /**
  35858. * Specifies whether or not this material should be rendered in alpha test mode.
  35859. */
  35860. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35861. if (this._forceAlphaTest) {
  35862. return true;
  35863. }
  35864. if (this._linkRefractionWithTransparency) {
  35865. return false;
  35866. }
  35867. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35868. };
  35869. /**
  35870. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35871. */
  35872. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35873. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35874. };
  35875. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35876. return this._albedoTexture;
  35877. };
  35878. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35879. var _this = this;
  35880. if (subMesh.effect && this.isFrozen) {
  35881. if (this._wasPreviouslyReady) {
  35882. return true;
  35883. }
  35884. }
  35885. if (!subMesh._materialDefines) {
  35886. subMesh._materialDefines = new PBRMaterialDefines();
  35887. }
  35888. var scene = this.getScene();
  35889. var defines = subMesh._materialDefines;
  35890. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35891. if (defines._renderId === scene.getRenderId()) {
  35892. return true;
  35893. }
  35894. }
  35895. var engine = scene.getEngine();
  35896. // Lights
  35897. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35898. defines._needNormals = true;
  35899. // Textures
  35900. if (defines._areTexturesDirty) {
  35901. defines._needUVs = false;
  35902. if (scene.texturesEnabled) {
  35903. if (scene.getEngine().getCaps().textureLOD) {
  35904. defines.LODBASEDMICROSFURACE = true;
  35905. }
  35906. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35907. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35908. return false;
  35909. }
  35910. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35911. }
  35912. else {
  35913. defines.ALBEDO = false;
  35914. }
  35915. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35916. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35917. return false;
  35918. }
  35919. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35920. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35921. }
  35922. else {
  35923. defines.AMBIENT = false;
  35924. }
  35925. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35926. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35927. return false;
  35928. }
  35929. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35930. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35931. }
  35932. else {
  35933. defines.OPACITY = false;
  35934. }
  35935. var reflectionTexture = this._getReflectionTexture();
  35936. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35937. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35938. return false;
  35939. }
  35940. defines.REFLECTION = true;
  35941. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35942. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35943. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35944. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35945. defines.INVERTCUBICMAP = true;
  35946. }
  35947. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35948. switch (reflectionTexture.coordinatesMode) {
  35949. case BABYLON.Texture.CUBIC_MODE:
  35950. case BABYLON.Texture.INVCUBIC_MODE:
  35951. defines.REFLECTIONMAP_CUBIC = true;
  35952. break;
  35953. case BABYLON.Texture.EXPLICIT_MODE:
  35954. defines.REFLECTIONMAP_EXPLICIT = true;
  35955. break;
  35956. case BABYLON.Texture.PLANAR_MODE:
  35957. defines.REFLECTIONMAP_PLANAR = true;
  35958. break;
  35959. case BABYLON.Texture.PROJECTION_MODE:
  35960. defines.REFLECTIONMAP_PROJECTION = true;
  35961. break;
  35962. case BABYLON.Texture.SKYBOX_MODE:
  35963. defines.REFLECTIONMAP_SKYBOX = true;
  35964. break;
  35965. case BABYLON.Texture.SPHERICAL_MODE:
  35966. defines.REFLECTIONMAP_SPHERICAL = true;
  35967. break;
  35968. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35969. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35970. break;
  35971. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35972. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35973. break;
  35974. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35975. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35976. break;
  35977. }
  35978. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35979. if (reflectionTexture.sphericalPolynomial) {
  35980. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35981. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35982. defines.USESPHERICALINVERTEX = false;
  35983. }
  35984. else {
  35985. defines.USESPHERICALINVERTEX = true;
  35986. }
  35987. }
  35988. }
  35989. }
  35990. else {
  35991. defines.REFLECTION = false;
  35992. defines.REFLECTIONMAP_3D = false;
  35993. defines.REFLECTIONMAP_SPHERICAL = false;
  35994. defines.REFLECTIONMAP_PLANAR = false;
  35995. defines.REFLECTIONMAP_CUBIC = false;
  35996. defines.REFLECTIONMAP_PROJECTION = false;
  35997. defines.REFLECTIONMAP_SKYBOX = false;
  35998. defines.REFLECTIONMAP_EXPLICIT = false;
  35999. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36000. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36001. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36002. defines.INVERTCUBICMAP = false;
  36003. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36004. defines.USESPHERICALINVERTEX = false;
  36005. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36006. defines.LODINREFLECTIONALPHA = false;
  36007. defines.GAMMAREFLECTION = false;
  36008. }
  36009. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36010. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36011. return false;
  36012. }
  36013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36014. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36015. }
  36016. else {
  36017. defines.LIGHTMAP = false;
  36018. }
  36019. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36020. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36021. return false;
  36022. }
  36023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36024. }
  36025. else {
  36026. defines.EMISSIVE = false;
  36027. }
  36028. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36029. if (this._metallicTexture) {
  36030. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36031. return false;
  36032. }
  36033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36034. defines.METALLICWORKFLOW = true;
  36035. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36036. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36037. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36038. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36039. }
  36040. else if (this._reflectivityTexture) {
  36041. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36042. return false;
  36043. }
  36044. defines.METALLICWORKFLOW = false;
  36045. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36046. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36047. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36048. }
  36049. else {
  36050. defines.METALLICWORKFLOW = false;
  36051. defines.REFLECTIVITY = false;
  36052. }
  36053. if (this._microSurfaceTexture) {
  36054. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36055. return false;
  36056. }
  36057. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36058. }
  36059. else {
  36060. defines.MICROSURFACEMAP = false;
  36061. }
  36062. }
  36063. else {
  36064. defines.REFLECTIVITY = false;
  36065. defines.MICROSURFACEMAP = false;
  36066. }
  36067. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36068. // Bump texure can not be none blocking.
  36069. if (!this._bumpTexture.isReady()) {
  36070. return false;
  36071. }
  36072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36073. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36074. defines.PARALLAX = true;
  36075. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36076. }
  36077. else {
  36078. defines.PARALLAX = false;
  36079. }
  36080. }
  36081. else {
  36082. defines.BUMP = false;
  36083. }
  36084. var refractionTexture = this._getRefractionTexture();
  36085. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36086. if (!refractionTexture.isReadyOrNotBlocking()) {
  36087. return false;
  36088. }
  36089. defines.REFRACTION = true;
  36090. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36091. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36092. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  36093. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36094. if (this._linkRefractionWithTransparency) {
  36095. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36096. }
  36097. }
  36098. else {
  36099. defines.REFRACTION = false;
  36100. }
  36101. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36102. // This is blocking.
  36103. if (!this._environmentBRDFTexture.isReady()) {
  36104. return false;
  36105. }
  36106. defines.ENVIRONMENTBRDF = true;
  36107. }
  36108. else {
  36109. defines.ENVIRONMENTBRDF = false;
  36110. }
  36111. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36112. defines.ALPHAFROMALBEDO = true;
  36113. }
  36114. else {
  36115. defines.ALPHAFROMALBEDO = false;
  36116. }
  36117. }
  36118. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36119. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36120. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36121. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36122. defines.METALLICWORKFLOW = true;
  36123. }
  36124. else {
  36125. defines.METALLICWORKFLOW = false;
  36126. }
  36127. if (!this.backFaceCulling && this._twoSidedLighting) {
  36128. defines.TWOSIDEDLIGHTING = true;
  36129. }
  36130. else {
  36131. defines.TWOSIDEDLIGHTING = false;
  36132. }
  36133. defines.ALPHATESTVALUE = this._alphaCutOff;
  36134. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36135. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36136. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36137. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36138. }
  36139. if (defines._areImageProcessingDirty) {
  36140. if (!this._imageProcessingConfiguration.isReady()) {
  36141. return false;
  36142. }
  36143. this._imageProcessingConfiguration.prepareDefines(defines);
  36144. }
  36145. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36146. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36147. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36148. // Misc.
  36149. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36150. // Values that need to be evaluated on every frame
  36151. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36152. // Attribs
  36153. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  36154. if (mesh) {
  36155. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36156. mesh.createNormals(true);
  36157. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  36158. }
  36159. }
  36160. }
  36161. // Get correct effect
  36162. if (defines.isDirty) {
  36163. defines.markAsProcessed();
  36164. scene.resetCachedMaterial();
  36165. // Fallbacks
  36166. var fallbacks = new BABYLON.EffectFallbacks();
  36167. var fallbackRank = 0;
  36168. if (defines.USESPHERICALINVERTEX) {
  36169. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36170. }
  36171. if (defines.FOG) {
  36172. fallbacks.addFallback(fallbackRank, "FOG");
  36173. }
  36174. if (defines.POINTSIZE) {
  36175. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36176. }
  36177. if (defines.LOGARITHMICDEPTH) {
  36178. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36179. }
  36180. if (defines.PARALLAX) {
  36181. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36182. }
  36183. if (defines.PARALLAXOCCLUSION) {
  36184. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36185. }
  36186. if (defines.ENVIRONMENTBRDF) {
  36187. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36188. }
  36189. if (defines.TANGENT) {
  36190. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36191. }
  36192. if (defines.BUMP) {
  36193. fallbacks.addFallback(fallbackRank++, "BUMP");
  36194. }
  36195. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36196. if (defines.SPECULARTERM) {
  36197. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36198. }
  36199. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36200. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36201. }
  36202. if (defines.LIGHTMAP) {
  36203. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36204. }
  36205. if (defines.NORMAL) {
  36206. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36207. }
  36208. if (defines.AMBIENT) {
  36209. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36210. }
  36211. if (defines.EMISSIVE) {
  36212. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36213. }
  36214. if (defines.VERTEXCOLOR) {
  36215. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36216. }
  36217. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36218. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36219. }
  36220. if (defines.MORPHTARGETS) {
  36221. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36222. }
  36223. //Attributes
  36224. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36225. if (defines.NORMAL) {
  36226. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36227. }
  36228. if (defines.TANGENT) {
  36229. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36230. }
  36231. if (defines.UV1) {
  36232. attribs.push(BABYLON.VertexBuffer.UVKind);
  36233. }
  36234. if (defines.UV2) {
  36235. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36236. }
  36237. if (defines.VERTEXCOLOR) {
  36238. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36239. }
  36240. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36241. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36242. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36243. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36244. "vFogInfos", "vFogColor", "pointSize",
  36245. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36246. "mBones",
  36247. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36248. "vLightingIntensity",
  36249. "logarithmicDepthConstant",
  36250. "vSphericalX", "vSphericalY", "vSphericalZ",
  36251. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36252. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36253. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36254. "vTangentSpaceParams"
  36255. ];
  36256. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36257. "bumpSampler", "lightmapSampler", "opacitySampler",
  36258. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36259. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36260. "microSurfaceSampler", "environmentBrdfSampler"];
  36261. var uniformBuffers = ["Material", "Scene"];
  36262. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36263. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36264. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36265. uniformsNames: uniforms,
  36266. uniformBuffersNames: uniformBuffers,
  36267. samplers: samplers,
  36268. defines: defines,
  36269. maxSimultaneousLights: this._maxSimultaneousLights
  36270. });
  36271. var onCompiled = function (effect) {
  36272. if (_this.onCompiled) {
  36273. _this.onCompiled(effect);
  36274. }
  36275. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36276. };
  36277. var join = defines.toString();
  36278. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36279. attributes: attribs,
  36280. uniformsNames: uniforms,
  36281. uniformBuffersNames: uniformBuffers,
  36282. samplers: samplers,
  36283. defines: join,
  36284. fallbacks: fallbacks,
  36285. onCompiled: onCompiled,
  36286. onError: this.onError,
  36287. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36288. }, engine), defines);
  36289. this.buildUniformLayout();
  36290. }
  36291. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36292. return false;
  36293. }
  36294. defines._renderId = scene.getRenderId();
  36295. this._wasPreviouslyReady = true;
  36296. return true;
  36297. };
  36298. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36299. // Order is important !
  36300. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36301. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36302. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36303. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36304. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36305. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36306. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36307. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36308. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36309. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36310. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36311. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36312. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36313. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36314. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36315. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36316. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36317. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36318. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36319. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36320. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36321. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36322. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36323. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36324. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36325. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36326. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36327. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36328. this._uniformBuffer.addUniform("pointSize", 1);
  36329. this._uniformBuffer.create();
  36330. };
  36331. PBRBaseMaterial.prototype.unbind = function () {
  36332. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36333. this._uniformBuffer.setTexture("reflectionSampler", null);
  36334. }
  36335. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36336. this._uniformBuffer.setTexture("refractionSampler", null);
  36337. }
  36338. _super.prototype.unbind.call(this);
  36339. };
  36340. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36341. this._activeEffect.setMatrix("world", world);
  36342. };
  36343. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36344. var scene = this.getScene();
  36345. var defines = subMesh._materialDefines;
  36346. if (!defines) {
  36347. return;
  36348. }
  36349. var effect = subMesh.effect;
  36350. if (!effect) {
  36351. return;
  36352. }
  36353. this._activeEffect = effect;
  36354. // Matrices
  36355. this.bindOnlyWorldMatrix(world);
  36356. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36357. // Bones
  36358. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36359. var reflectionTexture = null;
  36360. if (mustRebind) {
  36361. this._uniformBuffer.bindToEffect(effect, "Material");
  36362. this.bindViewProjection(effect);
  36363. reflectionTexture = this._getReflectionTexture();
  36364. var refractionTexture = this._getRefractionTexture();
  36365. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36366. // Texture uniforms
  36367. if (scene.texturesEnabled) {
  36368. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36369. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36370. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36371. }
  36372. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36373. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36374. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36375. }
  36376. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36377. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36378. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36379. }
  36380. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36381. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36382. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36383. var polynomials = reflectionTexture.sphericalPolynomial;
  36384. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36385. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36386. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36387. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36388. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36389. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36390. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36391. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36392. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36393. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36394. }
  36395. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36396. }
  36397. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36398. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36399. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36400. }
  36401. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36402. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36403. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36404. }
  36405. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36406. if (this._metallicTexture) {
  36407. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36408. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36409. }
  36410. else if (this._reflectivityTexture) {
  36411. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36412. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36413. }
  36414. if (this._microSurfaceTexture) {
  36415. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36416. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36417. }
  36418. }
  36419. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36420. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36421. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36422. if (scene._mirroredCameraPosition) {
  36423. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36424. }
  36425. else {
  36426. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36427. }
  36428. }
  36429. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36430. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36431. var depth = 1.0;
  36432. if (!refractionTexture.isCube) {
  36433. if (refractionTexture.depth) {
  36434. depth = refractionTexture.depth;
  36435. }
  36436. }
  36437. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36438. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36439. }
  36440. }
  36441. // Point size
  36442. if (this.pointsCloud) {
  36443. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36444. }
  36445. // Colors
  36446. if (defines.METALLICWORKFLOW) {
  36447. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36448. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36449. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36450. }
  36451. else {
  36452. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36453. }
  36454. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36455. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36456. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36457. // Misc
  36458. this._lightingInfos.x = this._directIntensity;
  36459. this._lightingInfos.y = this._emissiveIntensity;
  36460. this._lightingInfos.z = this._environmentIntensity;
  36461. this._lightingInfos.w = this._specularIntensity;
  36462. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36463. }
  36464. // Textures
  36465. if (scene.texturesEnabled) {
  36466. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36467. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36468. }
  36469. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36470. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36471. }
  36472. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36473. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36474. }
  36475. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36476. if (defines.LODBASEDMICROSFURACE) {
  36477. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36478. }
  36479. else {
  36480. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36481. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36482. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36483. }
  36484. }
  36485. if (defines.ENVIRONMENTBRDF) {
  36486. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36487. }
  36488. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36489. if (defines.LODBASEDMICROSFURACE) {
  36490. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36491. }
  36492. else {
  36493. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36494. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36495. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36496. }
  36497. }
  36498. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36499. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36500. }
  36501. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36502. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36503. }
  36504. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36505. if (this._metallicTexture) {
  36506. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36507. }
  36508. else if (this._reflectivityTexture) {
  36509. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36510. }
  36511. if (this._microSurfaceTexture) {
  36512. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36513. }
  36514. }
  36515. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36516. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36517. }
  36518. }
  36519. // Clip plane
  36520. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36521. // Colors
  36522. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36523. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36524. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36525. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36526. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36527. }
  36528. if (mustRebind || !this.isFrozen) {
  36529. // Lights
  36530. if (scene.lightsEnabled && !this._disableLighting) {
  36531. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36532. }
  36533. // View
  36534. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36535. this.bindView(effect);
  36536. }
  36537. // Fog
  36538. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36539. // Morph targets
  36540. if (defines.NUM_MORPH_INFLUENCERS) {
  36541. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36542. }
  36543. // image processing
  36544. this._imageProcessingConfiguration.bind(this._activeEffect);
  36545. // Log. depth
  36546. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36547. }
  36548. this._uniformBuffer.update();
  36549. this._afterBind(mesh);
  36550. };
  36551. PBRBaseMaterial.prototype.getAnimatables = function () {
  36552. var results = [];
  36553. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36554. results.push(this._albedoTexture);
  36555. }
  36556. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36557. results.push(this._ambientTexture);
  36558. }
  36559. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36560. results.push(this._opacityTexture);
  36561. }
  36562. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36563. results.push(this._reflectionTexture);
  36564. }
  36565. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36566. results.push(this._emissiveTexture);
  36567. }
  36568. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36569. results.push(this._metallicTexture);
  36570. }
  36571. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36572. results.push(this._reflectivityTexture);
  36573. }
  36574. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36575. results.push(this._bumpTexture);
  36576. }
  36577. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36578. results.push(this._lightmapTexture);
  36579. }
  36580. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36581. results.push(this._refractionTexture);
  36582. }
  36583. return results;
  36584. };
  36585. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36586. if (this._reflectionTexture) {
  36587. return this._reflectionTexture;
  36588. }
  36589. return this.getScene().environmentTexture;
  36590. };
  36591. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36592. if (this._refractionTexture) {
  36593. return this._refractionTexture;
  36594. }
  36595. if (this._linkRefractionWithTransparency) {
  36596. return this.getScene().environmentTexture;
  36597. }
  36598. return null;
  36599. };
  36600. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36601. if (forceDisposeTextures) {
  36602. if (this._albedoTexture) {
  36603. this._albedoTexture.dispose();
  36604. }
  36605. if (this._ambientTexture) {
  36606. this._ambientTexture.dispose();
  36607. }
  36608. if (this._opacityTexture) {
  36609. this._opacityTexture.dispose();
  36610. }
  36611. if (this._reflectionTexture) {
  36612. this._reflectionTexture.dispose();
  36613. }
  36614. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36615. this._environmentBRDFTexture.dispose();
  36616. }
  36617. if (this._emissiveTexture) {
  36618. this._emissiveTexture.dispose();
  36619. }
  36620. if (this._metallicTexture) {
  36621. this._metallicTexture.dispose();
  36622. }
  36623. if (this._reflectivityTexture) {
  36624. this._reflectivityTexture.dispose();
  36625. }
  36626. if (this._bumpTexture) {
  36627. this._bumpTexture.dispose();
  36628. }
  36629. if (this._lightmapTexture) {
  36630. this._lightmapTexture.dispose();
  36631. }
  36632. if (this._refractionTexture) {
  36633. this._refractionTexture.dispose();
  36634. }
  36635. }
  36636. this._renderTargets.dispose();
  36637. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36638. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36639. }
  36640. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36641. };
  36642. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36643. __decorate([
  36644. BABYLON.serializeAsImageProcessingConfiguration()
  36645. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36646. __decorate([
  36647. BABYLON.serialize()
  36648. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36649. __decorate([
  36650. BABYLON.serialize()
  36651. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36652. return PBRBaseMaterial;
  36653. }(BABYLON.PushMaterial));
  36654. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36655. })(BABYLON || (BABYLON = {}));
  36656. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36657. var BABYLON;
  36658. (function (BABYLON) {
  36659. var Internals;
  36660. (function (Internals) {
  36661. /**
  36662. * The Physically based simple base material of BJS.
  36663. *
  36664. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36665. * It is used as the base class for both the specGloss and metalRough conventions.
  36666. */
  36667. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36668. __extends(PBRBaseSimpleMaterial, _super);
  36669. /**
  36670. * Instantiates a new PBRMaterial instance.
  36671. *
  36672. * @param name The material name
  36673. * @param scene The scene the material will be use in.
  36674. */
  36675. function PBRBaseSimpleMaterial(name, scene) {
  36676. var _this = _super.call(this, name, scene) || this;
  36677. /**
  36678. * Number of Simultaneous lights allowed on the material.
  36679. */
  36680. _this.maxSimultaneousLights = 4;
  36681. /**
  36682. * If sets to true, disables all the lights affecting the material.
  36683. */
  36684. _this.disableLighting = false;
  36685. /**
  36686. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36687. */
  36688. _this.invertNormalMapX = false;
  36689. /**
  36690. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36691. */
  36692. _this.invertNormalMapY = false;
  36693. /**
  36694. * Emissivie color used to self-illuminate the model.
  36695. */
  36696. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36697. /**
  36698. * Occlusion Channel Strenght.
  36699. */
  36700. _this.occlusionStrength = 1.0;
  36701. _this.useLightmapAsShadowmap = false;
  36702. _this._useAlphaFromAlbedoTexture = true;
  36703. _this._useAmbientInGrayScale = true;
  36704. return _this;
  36705. }
  36706. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36707. /**
  36708. * Gets the current double sided mode.
  36709. */
  36710. get: function () {
  36711. return this._twoSidedLighting;
  36712. },
  36713. /**
  36714. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36715. */
  36716. set: function (value) {
  36717. if (this._twoSidedLighting === value) {
  36718. return;
  36719. }
  36720. this._twoSidedLighting = value;
  36721. this.backFaceCulling = !value;
  36722. this._markAllSubMeshesAsTexturesDirty();
  36723. },
  36724. enumerable: true,
  36725. configurable: true
  36726. });
  36727. /**
  36728. * Return the active textures of the material.
  36729. */
  36730. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36731. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36732. if (this.environmentTexture) {
  36733. activeTextures.push(this.environmentTexture);
  36734. }
  36735. if (this.normalTexture) {
  36736. activeTextures.push(this.normalTexture);
  36737. }
  36738. if (this.emissiveTexture) {
  36739. activeTextures.push(this.emissiveTexture);
  36740. }
  36741. if (this.occlusionTexture) {
  36742. activeTextures.push(this.occlusionTexture);
  36743. }
  36744. if (this.lightmapTexture) {
  36745. activeTextures.push(this.lightmapTexture);
  36746. }
  36747. return activeTextures;
  36748. };
  36749. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  36750. if (_super.prototype.hasTexture.call(this, texture)) {
  36751. return true;
  36752. }
  36753. if (this.lightmapTexture === texture) {
  36754. return true;
  36755. }
  36756. return false;
  36757. };
  36758. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36759. return "PBRBaseSimpleMaterial";
  36760. };
  36761. __decorate([
  36762. BABYLON.serialize(),
  36763. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36764. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36765. __decorate([
  36766. BABYLON.serialize(),
  36767. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36768. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36769. __decorate([
  36770. BABYLON.serializeAsTexture(),
  36771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36772. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36773. __decorate([
  36774. BABYLON.serialize(),
  36775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36776. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36777. __decorate([
  36778. BABYLON.serialize(),
  36779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36780. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36781. __decorate([
  36782. BABYLON.serializeAsTexture(),
  36783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36784. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36785. __decorate([
  36786. BABYLON.serializeAsColor3("emissive"),
  36787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36788. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36789. __decorate([
  36790. BABYLON.serializeAsTexture(),
  36791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36792. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36793. __decorate([
  36794. BABYLON.serialize(),
  36795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36796. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36797. __decorate([
  36798. BABYLON.serializeAsTexture(),
  36799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36800. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36801. __decorate([
  36802. BABYLON.serialize(),
  36803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36804. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36805. __decorate([
  36806. BABYLON.serialize()
  36807. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36808. __decorate([
  36809. BABYLON.serializeAsTexture(),
  36810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36811. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  36812. __decorate([
  36813. BABYLON.serialize(),
  36814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36815. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36816. return PBRBaseSimpleMaterial;
  36817. }(BABYLON.PBRBaseMaterial));
  36818. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36819. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36820. })(BABYLON || (BABYLON = {}));
  36821. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36822. var BABYLON;
  36823. (function (BABYLON) {
  36824. /**
  36825. * The Physically based material of BJS.
  36826. *
  36827. * This offers the main features of a standard PBR material.
  36828. * For more information, please refer to the documentation :
  36829. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36830. */
  36831. var PBRMaterial = /** @class */ (function (_super) {
  36832. __extends(PBRMaterial, _super);
  36833. /**
  36834. * Instantiates a new PBRMaterial instance.
  36835. *
  36836. * @param name The material name
  36837. * @param scene The scene the material will be use in.
  36838. */
  36839. function PBRMaterial(name, scene) {
  36840. var _this = _super.call(this, name, scene) || this;
  36841. /**
  36842. * Intensity of the direct lights e.g. the four lights available in your scene.
  36843. * This impacts both the direct diffuse and specular highlights.
  36844. */
  36845. _this.directIntensity = 1.0;
  36846. /**
  36847. * Intensity of the emissive part of the material.
  36848. * This helps controlling the emissive effect without modifying the emissive color.
  36849. */
  36850. _this.emissiveIntensity = 1.0;
  36851. /**
  36852. * Intensity of the environment e.g. how much the environment will light the object
  36853. * either through harmonics for rough material or through the refelction for shiny ones.
  36854. */
  36855. _this.environmentIntensity = 1.0;
  36856. /**
  36857. * This is a special control allowing the reduction of the specular highlights coming from the
  36858. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36859. */
  36860. _this.specularIntensity = 1.0;
  36861. /**
  36862. * Debug Control allowing disabling the bump map on this material.
  36863. */
  36864. _this.disableBumpMap = false;
  36865. /**
  36866. * AKA Occlusion Texture Intensity in other nomenclature.
  36867. */
  36868. _this.ambientTextureStrength = 1.0;
  36869. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36870. /**
  36871. * AKA Diffuse Color in other nomenclature.
  36872. */
  36873. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36874. /**
  36875. * AKA Specular Color in other nomenclature.
  36876. */
  36877. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36878. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36879. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36880. /**
  36881. * AKA Glossiness in other nomenclature.
  36882. */
  36883. _this.microSurface = 1.0;
  36884. /**
  36885. * source material index of refraction (IOR)' / 'destination material IOR.
  36886. */
  36887. _this.indexOfRefraction = 0.66;
  36888. /**
  36889. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36890. */
  36891. _this.invertRefractionY = false;
  36892. /**
  36893. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36894. * Materials half opaque for instance using refraction could benefit from this control.
  36895. */
  36896. _this.linkRefractionWithTransparency = false;
  36897. _this.useLightmapAsShadowmap = false;
  36898. /**
  36899. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36900. */
  36901. _this.useAlphaFromAlbedoTexture = false;
  36902. /**
  36903. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36904. */
  36905. _this.forceAlphaTest = false;
  36906. /**
  36907. * Defines the alpha limits in alpha test mode.
  36908. */
  36909. _this.alphaCutOff = 0.4;
  36910. /**
  36911. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36912. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36913. */
  36914. _this.useSpecularOverAlpha = true;
  36915. /**
  36916. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36917. */
  36918. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36919. /**
  36920. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36921. */
  36922. _this.useRoughnessFromMetallicTextureAlpha = true;
  36923. /**
  36924. * Specifies if the metallic texture contains the roughness information in its green channel.
  36925. */
  36926. _this.useRoughnessFromMetallicTextureGreen = false;
  36927. /**
  36928. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36929. */
  36930. _this.useMetallnessFromMetallicTextureBlue = false;
  36931. /**
  36932. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36933. */
  36934. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36935. /**
  36936. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36937. */
  36938. _this.useAmbientInGrayScale = false;
  36939. /**
  36940. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36941. * The material will try to infer what glossiness each pixel should be.
  36942. */
  36943. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36944. /**
  36945. * BJS is using an harcoded light falloff based on a manually sets up range.
  36946. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36947. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36948. */
  36949. _this.usePhysicalLightFalloff = true;
  36950. /**
  36951. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36952. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36953. */
  36954. _this.useRadianceOverAlpha = true;
  36955. /**
  36956. * Allows using the bump map in parallax mode.
  36957. */
  36958. _this.useParallax = false;
  36959. /**
  36960. * Allows using the bump map in parallax occlusion mode.
  36961. */
  36962. _this.useParallaxOcclusion = false;
  36963. /**
  36964. * Controls the scale bias of the parallax mode.
  36965. */
  36966. _this.parallaxScaleBias = 0.05;
  36967. /**
  36968. * If sets to true, disables all the lights affecting the material.
  36969. */
  36970. _this.disableLighting = false;
  36971. /**
  36972. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36973. */
  36974. _this.forceIrradianceInFragment = false;
  36975. /**
  36976. * Number of Simultaneous lights allowed on the material.
  36977. */
  36978. _this.maxSimultaneousLights = 4;
  36979. /**
  36980. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36981. */
  36982. _this.invertNormalMapX = false;
  36983. /**
  36984. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36985. */
  36986. _this.invertNormalMapY = false;
  36987. /**
  36988. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36989. */
  36990. _this.twoSidedLighting = false;
  36991. /**
  36992. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36993. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36994. */
  36995. _this.useAlphaFresnel = false;
  36996. /**
  36997. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36998. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36999. */
  37000. _this.useLinearAlphaFresnel = false;
  37001. /**
  37002. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37003. * And/Or occlude the blended part.
  37004. */
  37005. _this.environmentBRDFTexture = null;
  37006. /**
  37007. * Force normal to face away from face.
  37008. * (Temporary internal fix to remove before 3.1)
  37009. */
  37010. _this.forceNormalForward = false;
  37011. /**
  37012. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37013. * makes the reflect vector face the model (under horizon).
  37014. */
  37015. _this.useHorizonOcclusion = true;
  37016. /**
  37017. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37018. * too much the area relying on ambient texture to define their ambient occlusion.
  37019. */
  37020. _this.useRadianceOcclusion = true;
  37021. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37022. return _this;
  37023. }
  37024. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37025. /**
  37026. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37027. */
  37028. get: function () {
  37029. return this._PBRMATERIAL_OPAQUE;
  37030. },
  37031. enumerable: true,
  37032. configurable: true
  37033. });
  37034. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37035. /**
  37036. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37037. */
  37038. get: function () {
  37039. return this._PBRMATERIAL_ALPHATEST;
  37040. },
  37041. enumerable: true,
  37042. configurable: true
  37043. });
  37044. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37045. /**
  37046. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37047. */
  37048. get: function () {
  37049. return this._PBRMATERIAL_ALPHABLEND;
  37050. },
  37051. enumerable: true,
  37052. configurable: true
  37053. });
  37054. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37055. /**
  37056. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37057. * They are also discarded below the alpha cutoff threshold to improve performances.
  37058. */
  37059. get: function () {
  37060. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37061. },
  37062. enumerable: true,
  37063. configurable: true
  37064. });
  37065. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37066. /**
  37067. * Gets the image processing configuration used either in this material.
  37068. */
  37069. get: function () {
  37070. return this._imageProcessingConfiguration;
  37071. },
  37072. /**
  37073. * Sets the Default image processing configuration used either in the this material.
  37074. *
  37075. * If sets to null, the scene one is in use.
  37076. */
  37077. set: function (value) {
  37078. this._attachImageProcessingConfiguration(value);
  37079. // Ensure the effect will be rebuilt.
  37080. this._markAllSubMeshesAsTexturesDirty();
  37081. },
  37082. enumerable: true,
  37083. configurable: true
  37084. });
  37085. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37086. /**
  37087. * Gets wether the color curves effect is enabled.
  37088. */
  37089. get: function () {
  37090. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37091. },
  37092. /**
  37093. * Sets wether the color curves effect is enabled.
  37094. */
  37095. set: function (value) {
  37096. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37102. /**
  37103. * Gets wether the color grading effect is enabled.
  37104. */
  37105. get: function () {
  37106. return this.imageProcessingConfiguration.colorGradingEnabled;
  37107. },
  37108. /**
  37109. * Gets wether the color grading effect is enabled.
  37110. */
  37111. set: function (value) {
  37112. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37118. /**
  37119. * Gets wether tonemapping is enabled or not.
  37120. */
  37121. get: function () {
  37122. return this._imageProcessingConfiguration.toneMappingEnabled;
  37123. },
  37124. /**
  37125. * Sets wether tonemapping is enabled or not
  37126. */
  37127. set: function (value) {
  37128. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37129. },
  37130. enumerable: true,
  37131. configurable: true
  37132. });
  37133. ;
  37134. ;
  37135. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37136. /**
  37137. * The camera exposure used on this material.
  37138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37139. * This corresponds to a photographic exposure.
  37140. */
  37141. get: function () {
  37142. return this._imageProcessingConfiguration.exposure;
  37143. },
  37144. /**
  37145. * The camera exposure used on this material.
  37146. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37147. * This corresponds to a photographic exposure.
  37148. */
  37149. set: function (value) {
  37150. this._imageProcessingConfiguration.exposure = value;
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. ;
  37156. ;
  37157. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37158. /**
  37159. * Gets The camera contrast used on this material.
  37160. */
  37161. get: function () {
  37162. return this._imageProcessingConfiguration.contrast;
  37163. },
  37164. /**
  37165. * Sets The camera contrast used on this material.
  37166. */
  37167. set: function (value) {
  37168. this._imageProcessingConfiguration.contrast = value;
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37174. /**
  37175. * Gets the Color Grading 2D Lookup Texture.
  37176. */
  37177. get: function () {
  37178. return this._imageProcessingConfiguration.colorGradingTexture;
  37179. },
  37180. /**
  37181. * Sets the Color Grading 2D Lookup Texture.
  37182. */
  37183. set: function (value) {
  37184. this._imageProcessingConfiguration.colorGradingTexture = value;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37190. /**
  37191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37193. * 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;
  37194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37195. */
  37196. get: function () {
  37197. return this._imageProcessingConfiguration.colorCurves;
  37198. },
  37199. /**
  37200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37202. * 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;
  37203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37204. */
  37205. set: function (value) {
  37206. this._imageProcessingConfiguration.colorCurves = value;
  37207. },
  37208. enumerable: true,
  37209. configurable: true
  37210. });
  37211. PBRMaterial.prototype.getClassName = function () {
  37212. return "PBRMaterial";
  37213. };
  37214. PBRMaterial.prototype.getActiveTextures = function () {
  37215. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37216. if (this._albedoTexture) {
  37217. activeTextures.push(this._albedoTexture);
  37218. }
  37219. if (this._ambientTexture) {
  37220. activeTextures.push(this._ambientTexture);
  37221. }
  37222. if (this._opacityTexture) {
  37223. activeTextures.push(this._opacityTexture);
  37224. }
  37225. if (this._reflectionTexture) {
  37226. activeTextures.push(this._reflectionTexture);
  37227. }
  37228. if (this._emissiveTexture) {
  37229. activeTextures.push(this._emissiveTexture);
  37230. }
  37231. if (this._reflectivityTexture) {
  37232. activeTextures.push(this._reflectivityTexture);
  37233. }
  37234. if (this._metallicTexture) {
  37235. activeTextures.push(this._metallicTexture);
  37236. }
  37237. if (this._microSurfaceTexture) {
  37238. activeTextures.push(this._microSurfaceTexture);
  37239. }
  37240. if (this._bumpTexture) {
  37241. activeTextures.push(this._bumpTexture);
  37242. }
  37243. if (this._lightmapTexture) {
  37244. activeTextures.push(this._lightmapTexture);
  37245. }
  37246. if (this._refractionTexture) {
  37247. activeTextures.push(this._refractionTexture);
  37248. }
  37249. return activeTextures;
  37250. };
  37251. PBRMaterial.prototype.hasTexture = function (texture) {
  37252. if (_super.prototype.hasTexture.call(this, texture)) {
  37253. return true;
  37254. }
  37255. if (this._albedoTexture === texture) {
  37256. return true;
  37257. }
  37258. if (this._ambientTexture === texture) {
  37259. return true;
  37260. }
  37261. if (this._opacityTexture === texture) {
  37262. return true;
  37263. }
  37264. if (this._reflectionTexture === texture) {
  37265. return true;
  37266. }
  37267. if (this._reflectivityTexture === texture) {
  37268. return true;
  37269. }
  37270. if (this._metallicTexture === texture) {
  37271. return true;
  37272. }
  37273. if (this._microSurfaceTexture === texture) {
  37274. return true;
  37275. }
  37276. if (this._bumpTexture === texture) {
  37277. return true;
  37278. }
  37279. if (this._lightmapTexture === texture) {
  37280. return true;
  37281. }
  37282. if (this._refractionTexture === texture) {
  37283. return true;
  37284. }
  37285. return false;
  37286. };
  37287. PBRMaterial.prototype.clone = function (name) {
  37288. var _this = this;
  37289. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37290. clone.id = name;
  37291. clone.name = name;
  37292. return clone;
  37293. };
  37294. PBRMaterial.prototype.serialize = function () {
  37295. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37296. serializationObject.customType = "BABYLON.PBRMaterial";
  37297. return serializationObject;
  37298. };
  37299. // Statics
  37300. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37301. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37302. };
  37303. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37304. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37305. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37306. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37307. __decorate([
  37308. BABYLON.serialize(),
  37309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37310. ], PBRMaterial.prototype, "directIntensity", void 0);
  37311. __decorate([
  37312. BABYLON.serialize(),
  37313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37314. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37315. __decorate([
  37316. BABYLON.serialize(),
  37317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37318. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37319. __decorate([
  37320. BABYLON.serialize(),
  37321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37322. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37323. __decorate([
  37324. BABYLON.serialize(),
  37325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37326. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37327. __decorate([
  37328. BABYLON.serializeAsTexture(),
  37329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37330. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37331. __decorate([
  37332. BABYLON.serializeAsTexture(),
  37333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37334. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37335. __decorate([
  37336. BABYLON.serialize(),
  37337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37338. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37339. __decorate([
  37340. BABYLON.serializeAsTexture(),
  37341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37342. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37343. __decorate([
  37344. BABYLON.serializeAsTexture(),
  37345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37346. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37347. __decorate([
  37348. BABYLON.serializeAsTexture(),
  37349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37350. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37351. __decorate([
  37352. BABYLON.serializeAsTexture(),
  37353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37354. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37355. __decorate([
  37356. BABYLON.serializeAsTexture(),
  37357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37358. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37359. __decorate([
  37360. BABYLON.serialize(),
  37361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37362. ], PBRMaterial.prototype, "metallic", void 0);
  37363. __decorate([
  37364. BABYLON.serialize(),
  37365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37366. ], PBRMaterial.prototype, "roughness", void 0);
  37367. __decorate([
  37368. BABYLON.serializeAsTexture(),
  37369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37370. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37371. __decorate([
  37372. BABYLON.serializeAsTexture(),
  37373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37374. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37375. __decorate([
  37376. BABYLON.serializeAsTexture(),
  37377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37378. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37379. __decorate([
  37380. BABYLON.serializeAsTexture(),
  37381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37382. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37383. __decorate([
  37384. BABYLON.serializeAsColor3("ambient"),
  37385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37386. ], PBRMaterial.prototype, "ambientColor", void 0);
  37387. __decorate([
  37388. BABYLON.serializeAsColor3("albedo"),
  37389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37390. ], PBRMaterial.prototype, "albedoColor", void 0);
  37391. __decorate([
  37392. BABYLON.serializeAsColor3("reflectivity"),
  37393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37394. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37395. __decorate([
  37396. BABYLON.serializeAsColor3("reflection"),
  37397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37398. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37399. __decorate([
  37400. BABYLON.serializeAsColor3("emissive"),
  37401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37402. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37403. __decorate([
  37404. BABYLON.serialize(),
  37405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37406. ], PBRMaterial.prototype, "microSurface", void 0);
  37407. __decorate([
  37408. BABYLON.serialize(),
  37409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37410. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37411. __decorate([
  37412. BABYLON.serialize(),
  37413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37414. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37415. __decorate([
  37416. BABYLON.serialize(),
  37417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37418. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37419. __decorate([
  37420. BABYLON.serialize(),
  37421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37422. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37423. __decorate([
  37424. BABYLON.serialize(),
  37425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37426. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37427. __decorate([
  37428. BABYLON.serialize(),
  37429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37430. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37431. __decorate([
  37432. BABYLON.serialize(),
  37433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37434. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37435. __decorate([
  37436. BABYLON.serialize(),
  37437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37438. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37439. __decorate([
  37440. BABYLON.serialize(),
  37441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37442. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37443. __decorate([
  37444. BABYLON.serialize(),
  37445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37446. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37447. __decorate([
  37448. BABYLON.serialize(),
  37449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37450. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37451. __decorate([
  37452. BABYLON.serialize(),
  37453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37454. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37455. __decorate([
  37456. BABYLON.serialize(),
  37457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37458. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37459. __decorate([
  37460. BABYLON.serialize(),
  37461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37462. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37463. __decorate([
  37464. BABYLON.serialize(),
  37465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37466. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37467. __decorate([
  37468. BABYLON.serialize(),
  37469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37470. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37471. __decorate([
  37472. BABYLON.serialize(),
  37473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37474. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37475. __decorate([
  37476. BABYLON.serialize(),
  37477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37478. ], PBRMaterial.prototype, "useParallax", void 0);
  37479. __decorate([
  37480. BABYLON.serialize(),
  37481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37482. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37483. __decorate([
  37484. BABYLON.serialize(),
  37485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37486. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37487. __decorate([
  37488. BABYLON.serialize(),
  37489. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37490. ], PBRMaterial.prototype, "disableLighting", void 0);
  37491. __decorate([
  37492. BABYLON.serialize(),
  37493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37494. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37495. __decorate([
  37496. BABYLON.serialize(),
  37497. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37498. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37499. __decorate([
  37500. BABYLON.serialize(),
  37501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37502. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37503. __decorate([
  37504. BABYLON.serialize(),
  37505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37506. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37507. __decorate([
  37508. BABYLON.serialize(),
  37509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37510. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37511. __decorate([
  37512. BABYLON.serialize(),
  37513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37514. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37515. __decorate([
  37516. BABYLON.serialize(),
  37517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37518. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37519. __decorate([
  37520. BABYLON.serializeAsTexture(),
  37521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37522. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37523. __decorate([
  37524. BABYLON.serialize(),
  37525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37526. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37527. __decorate([
  37528. BABYLON.serialize(),
  37529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37530. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37531. __decorate([
  37532. BABYLON.serialize(),
  37533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37534. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37535. return PBRMaterial;
  37536. }(BABYLON.PBRBaseMaterial));
  37537. BABYLON.PBRMaterial = PBRMaterial;
  37538. })(BABYLON || (BABYLON = {}));
  37539. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37540. var BABYLON;
  37541. (function (BABYLON) {
  37542. /**
  37543. * The PBR material of BJS following the metal roughness convention.
  37544. *
  37545. * This fits to the PBR convention in the GLTF definition:
  37546. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37547. */
  37548. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37549. __extends(PBRMetallicRoughnessMaterial, _super);
  37550. /**
  37551. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37552. *
  37553. * @param name The material name
  37554. * @param scene The scene the material will be use in.
  37555. */
  37556. function PBRMetallicRoughnessMaterial(name, scene) {
  37557. var _this = _super.call(this, name, scene) || this;
  37558. _this._useRoughnessFromMetallicTextureAlpha = false;
  37559. _this._useRoughnessFromMetallicTextureGreen = true;
  37560. _this._useMetallnessFromMetallicTextureBlue = true;
  37561. return _this;
  37562. }
  37563. /**
  37564. * Return the currrent class name of the material.
  37565. */
  37566. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37567. return "PBRMetallicRoughnessMaterial";
  37568. };
  37569. /**
  37570. * Return the active textures of the material.
  37571. */
  37572. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37573. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37574. if (this.baseTexture) {
  37575. activeTextures.push(this.baseTexture);
  37576. }
  37577. if (this.metallicRoughnessTexture) {
  37578. activeTextures.push(this.metallicRoughnessTexture);
  37579. }
  37580. return activeTextures;
  37581. };
  37582. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37583. if (_super.prototype.hasTexture.call(this, texture)) {
  37584. return true;
  37585. }
  37586. if (this.baseTexture === texture) {
  37587. return true;
  37588. }
  37589. if (this.metallicRoughnessTexture === texture) {
  37590. return true;
  37591. }
  37592. return false;
  37593. };
  37594. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37595. var _this = this;
  37596. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37597. clone.id = name;
  37598. clone.name = name;
  37599. return clone;
  37600. };
  37601. /**
  37602. * Serialize the material to a parsable JSON object.
  37603. */
  37604. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37605. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37606. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37607. return serializationObject;
  37608. };
  37609. /**
  37610. * Parses a JSON object correponding to the serialize function.
  37611. */
  37612. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37613. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37614. };
  37615. __decorate([
  37616. BABYLON.serializeAsColor3(),
  37617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37618. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37619. __decorate([
  37620. BABYLON.serializeAsTexture(),
  37621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37622. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37623. __decorate([
  37624. BABYLON.serialize(),
  37625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37626. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37627. __decorate([
  37628. BABYLON.serialize(),
  37629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37630. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37631. __decorate([
  37632. BABYLON.serializeAsTexture(),
  37633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37634. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37635. return PBRMetallicRoughnessMaterial;
  37636. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37637. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37638. })(BABYLON || (BABYLON = {}));
  37639. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37640. var BABYLON;
  37641. (function (BABYLON) {
  37642. /**
  37643. * The PBR material of BJS following the specular glossiness convention.
  37644. *
  37645. * This fits to the PBR convention in the GLTF definition:
  37646. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37647. */
  37648. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37649. __extends(PBRSpecularGlossinessMaterial, _super);
  37650. /**
  37651. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37652. *
  37653. * @param name The material name
  37654. * @param scene The scene the material will be use in.
  37655. */
  37656. function PBRSpecularGlossinessMaterial(name, scene) {
  37657. var _this = _super.call(this, name, scene) || this;
  37658. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37659. return _this;
  37660. }
  37661. /**
  37662. * Return the currrent class name of the material.
  37663. */
  37664. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37665. return "PBRSpecularGlossinessMaterial";
  37666. };
  37667. /**
  37668. * Return the active textures of the material.
  37669. */
  37670. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37671. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37672. if (this.diffuseTexture) {
  37673. activeTextures.push(this.diffuseTexture);
  37674. }
  37675. if (this.specularGlossinessTexture) {
  37676. activeTextures.push(this.specularGlossinessTexture);
  37677. }
  37678. return activeTextures;
  37679. };
  37680. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37681. if (_super.prototype.hasTexture.call(this, texture)) {
  37682. return true;
  37683. }
  37684. if (this.diffuseTexture === texture) {
  37685. return true;
  37686. }
  37687. if (this.specularGlossinessTexture === texture) {
  37688. return true;
  37689. }
  37690. return false;
  37691. };
  37692. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37693. var _this = this;
  37694. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37695. clone.id = name;
  37696. clone.name = name;
  37697. return clone;
  37698. };
  37699. /**
  37700. * Serialize the material to a parsable JSON object.
  37701. */
  37702. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37703. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37704. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37705. return serializationObject;
  37706. };
  37707. /**
  37708. * Parses a JSON object correponding to the serialize function.
  37709. */
  37710. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37711. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37712. };
  37713. __decorate([
  37714. BABYLON.serializeAsColor3("diffuse"),
  37715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37716. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37717. __decorate([
  37718. BABYLON.serializeAsTexture(),
  37719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37720. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37721. __decorate([
  37722. BABYLON.serializeAsColor3("specular"),
  37723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37724. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37725. __decorate([
  37726. BABYLON.serialize(),
  37727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37728. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37729. __decorate([
  37730. BABYLON.serializeAsTexture(),
  37731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37732. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37733. return PBRSpecularGlossinessMaterial;
  37734. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37735. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37736. })(BABYLON || (BABYLON = {}));
  37737. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37738. var BABYLON;
  37739. (function (BABYLON) {
  37740. BABYLON.CameraInputTypes = {};
  37741. var CameraInputsManager = /** @class */ (function () {
  37742. function CameraInputsManager(camera) {
  37743. this.attached = {};
  37744. this.camera = camera;
  37745. this.checkInputs = function () { };
  37746. }
  37747. CameraInputsManager.prototype.add = function (input) {
  37748. var type = input.getSimpleName();
  37749. if (this.attached[type]) {
  37750. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37751. return;
  37752. }
  37753. this.attached[type] = input;
  37754. input.camera = this.camera;
  37755. //for checkInputs, we are dynamically creating a function
  37756. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37757. if (input.checkInputs) {
  37758. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37759. }
  37760. if (this.attachedElement) {
  37761. input.attachControl(this.attachedElement);
  37762. }
  37763. };
  37764. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37765. for (var cam in this.attached) {
  37766. var input = this.attached[cam];
  37767. if (input === inputToRemove) {
  37768. input.detachControl(this.attachedElement);
  37769. input.camera = null;
  37770. delete this.attached[cam];
  37771. this.rebuildInputCheck();
  37772. }
  37773. }
  37774. };
  37775. CameraInputsManager.prototype.removeByType = function (inputType) {
  37776. for (var cam in this.attached) {
  37777. var input = this.attached[cam];
  37778. if (input.getClassName() === inputType) {
  37779. input.detachControl(this.attachedElement);
  37780. input.camera = null;
  37781. delete this.attached[cam];
  37782. this.rebuildInputCheck();
  37783. }
  37784. }
  37785. };
  37786. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37787. var current = this.checkInputs;
  37788. return function () {
  37789. current();
  37790. fn();
  37791. };
  37792. };
  37793. CameraInputsManager.prototype.attachInput = function (input) {
  37794. if (this.attachedElement) {
  37795. input.attachControl(this.attachedElement, this.noPreventDefault);
  37796. }
  37797. };
  37798. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37799. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37800. if (this.attachedElement) {
  37801. return;
  37802. }
  37803. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37804. this.attachedElement = element;
  37805. this.noPreventDefault = noPreventDefault;
  37806. for (var cam in this.attached) {
  37807. this.attached[cam].attachControl(element, noPreventDefault);
  37808. }
  37809. };
  37810. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37811. if (disconnect === void 0) { disconnect = false; }
  37812. if (this.attachedElement !== element) {
  37813. return;
  37814. }
  37815. for (var cam in this.attached) {
  37816. this.attached[cam].detachControl(element);
  37817. if (disconnect) {
  37818. this.attached[cam].camera = null;
  37819. }
  37820. }
  37821. this.attachedElement = null;
  37822. };
  37823. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37824. this.checkInputs = function () { };
  37825. for (var cam in this.attached) {
  37826. var input = this.attached[cam];
  37827. if (input.checkInputs) {
  37828. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37829. }
  37830. }
  37831. };
  37832. CameraInputsManager.prototype.clear = function () {
  37833. if (this.attachedElement) {
  37834. this.detachElement(this.attachedElement, true);
  37835. }
  37836. this.attached = {};
  37837. this.attachedElement = null;
  37838. this.checkInputs = function () { };
  37839. };
  37840. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37841. var inputs = {};
  37842. for (var cam in this.attached) {
  37843. var input = this.attached[cam];
  37844. var res = BABYLON.SerializationHelper.Serialize(input);
  37845. inputs[input.getClassName()] = res;
  37846. }
  37847. serializedCamera.inputsmgr = inputs;
  37848. };
  37849. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37850. var parsedInputs = parsedCamera.inputsmgr;
  37851. if (parsedInputs) {
  37852. this.clear();
  37853. for (var n in parsedInputs) {
  37854. var construct = BABYLON.CameraInputTypes[n];
  37855. if (construct) {
  37856. var parsedinput = parsedInputs[n];
  37857. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37858. this.add(input);
  37859. }
  37860. }
  37861. }
  37862. else {
  37863. //2016-03-08 this part is for managing backward compatibility
  37864. for (var n in this.attached) {
  37865. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37866. if (construct) {
  37867. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37868. this.remove(this.attached[n]);
  37869. this.add(input);
  37870. }
  37871. }
  37872. }
  37873. };
  37874. return CameraInputsManager;
  37875. }());
  37876. BABYLON.CameraInputsManager = CameraInputsManager;
  37877. })(BABYLON || (BABYLON = {}));
  37878. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37879. var BABYLON;
  37880. (function (BABYLON) {
  37881. var FreeCameraMouseInput = /** @class */ (function () {
  37882. function FreeCameraMouseInput(touchEnabled) {
  37883. if (touchEnabled === void 0) { touchEnabled = true; }
  37884. this.touchEnabled = touchEnabled;
  37885. this.buttons = [0, 1, 2];
  37886. this.angularSensibility = 2000.0;
  37887. this.previousPosition = null;
  37888. }
  37889. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37890. var _this = this;
  37891. var engine = this.camera.getEngine();
  37892. if (!this._pointerInput) {
  37893. this._pointerInput = function (p, s) {
  37894. var evt = p.event;
  37895. if (engine.isInVRExclusivePointerMode) {
  37896. return;
  37897. }
  37898. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37899. return;
  37900. }
  37901. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37902. return;
  37903. }
  37904. var srcElement = (evt.srcElement || evt.target);
  37905. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37906. try {
  37907. srcElement.setPointerCapture(evt.pointerId);
  37908. }
  37909. catch (e) {
  37910. //Nothing to do with the error. Execution will continue.
  37911. }
  37912. _this.previousPosition = {
  37913. x: evt.clientX,
  37914. y: evt.clientY
  37915. };
  37916. if (!noPreventDefault) {
  37917. evt.preventDefault();
  37918. element.focus();
  37919. }
  37920. }
  37921. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37922. try {
  37923. srcElement.releasePointerCapture(evt.pointerId);
  37924. }
  37925. catch (e) {
  37926. //Nothing to do with the error.
  37927. }
  37928. _this.previousPosition = null;
  37929. if (!noPreventDefault) {
  37930. evt.preventDefault();
  37931. }
  37932. }
  37933. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37934. if (!_this.previousPosition || engine.isPointerLock) {
  37935. return;
  37936. }
  37937. var offsetX = evt.clientX - _this.previousPosition.x;
  37938. var offsetY = evt.clientY - _this.previousPosition.y;
  37939. if (_this.camera.getScene().useRightHandedSystem) {
  37940. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37941. }
  37942. else {
  37943. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37944. }
  37945. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37946. _this.previousPosition = {
  37947. x: evt.clientX,
  37948. y: evt.clientY
  37949. };
  37950. if (!noPreventDefault) {
  37951. evt.preventDefault();
  37952. }
  37953. }
  37954. };
  37955. }
  37956. this._onMouseMove = function (evt) {
  37957. if (!engine.isPointerLock) {
  37958. return;
  37959. }
  37960. if (engine.isInVRExclusivePointerMode) {
  37961. return;
  37962. }
  37963. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37964. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37965. if (_this.camera.getScene().useRightHandedSystem) {
  37966. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37967. }
  37968. else {
  37969. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37970. }
  37971. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37972. _this.previousPosition = null;
  37973. if (!noPreventDefault) {
  37974. evt.preventDefault();
  37975. }
  37976. };
  37977. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37978. element.addEventListener("mousemove", this._onMouseMove, false);
  37979. };
  37980. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37981. if (this._observer && element) {
  37982. this.camera.getScene().onPointerObservable.remove(this._observer);
  37983. if (this._onMouseMove) {
  37984. element.removeEventListener("mousemove", this._onMouseMove);
  37985. }
  37986. this._observer = null;
  37987. this._onMouseMove = null;
  37988. this.previousPosition = null;
  37989. }
  37990. };
  37991. FreeCameraMouseInput.prototype.getClassName = function () {
  37992. return "FreeCameraMouseInput";
  37993. };
  37994. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37995. return "mouse";
  37996. };
  37997. __decorate([
  37998. BABYLON.serialize()
  37999. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38000. __decorate([
  38001. BABYLON.serialize()
  38002. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38003. return FreeCameraMouseInput;
  38004. }());
  38005. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38006. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38007. })(BABYLON || (BABYLON = {}));
  38008. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38009. var BABYLON;
  38010. (function (BABYLON) {
  38011. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38012. function FreeCameraKeyboardMoveInput() {
  38013. this._keys = new Array();
  38014. this.keysUp = [38];
  38015. this.keysDown = [40];
  38016. this.keysLeft = [37];
  38017. this.keysRight = [39];
  38018. }
  38019. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38020. var _this = this;
  38021. if (this._onCanvasBlurObserver) {
  38022. return;
  38023. }
  38024. this._scene = this.camera.getScene();
  38025. this._engine = this._scene.getEngine();
  38026. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38027. _this._keys = [];
  38028. });
  38029. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38030. var evt = info.event;
  38031. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38035. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38036. var index = _this._keys.indexOf(evt.keyCode);
  38037. if (index === -1) {
  38038. _this._keys.push(evt.keyCode);
  38039. }
  38040. if (!noPreventDefault) {
  38041. evt.preventDefault();
  38042. }
  38043. }
  38044. }
  38045. else {
  38046. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38047. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38048. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38049. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38050. var index = _this._keys.indexOf(evt.keyCode);
  38051. if (index >= 0) {
  38052. _this._keys.splice(index, 1);
  38053. }
  38054. if (!noPreventDefault) {
  38055. evt.preventDefault();
  38056. }
  38057. }
  38058. }
  38059. });
  38060. };
  38061. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38062. if (this._scene) {
  38063. if (this._onKeyboardObserver) {
  38064. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38065. }
  38066. if (this._onCanvasBlurObserver) {
  38067. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38068. }
  38069. this._onKeyboardObserver = null;
  38070. this._onCanvasBlurObserver = null;
  38071. }
  38072. this._keys = [];
  38073. };
  38074. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38075. if (this._onKeyboardObserver) {
  38076. var camera = this.camera;
  38077. // Keyboard
  38078. for (var index = 0; index < this._keys.length; index++) {
  38079. var keyCode = this._keys[index];
  38080. var speed = camera._computeLocalCameraSpeed();
  38081. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38082. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38083. }
  38084. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38085. camera._localDirection.copyFromFloats(0, 0, speed);
  38086. }
  38087. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38088. camera._localDirection.copyFromFloats(speed, 0, 0);
  38089. }
  38090. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38091. camera._localDirection.copyFromFloats(0, 0, -speed);
  38092. }
  38093. if (camera.getScene().useRightHandedSystem) {
  38094. camera._localDirection.z *= -1;
  38095. }
  38096. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38097. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38098. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38099. }
  38100. }
  38101. };
  38102. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38103. return "FreeCameraKeyboardMoveInput";
  38104. };
  38105. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38106. this._keys = [];
  38107. };
  38108. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38109. return "keyboard";
  38110. };
  38111. __decorate([
  38112. BABYLON.serialize()
  38113. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38114. __decorate([
  38115. BABYLON.serialize()
  38116. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38117. __decorate([
  38118. BABYLON.serialize()
  38119. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38120. __decorate([
  38121. BABYLON.serialize()
  38122. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38123. return FreeCameraKeyboardMoveInput;
  38124. }());
  38125. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38126. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38127. })(BABYLON || (BABYLON = {}));
  38128. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38129. var BABYLON;
  38130. (function (BABYLON) {
  38131. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38132. __extends(FreeCameraInputsManager, _super);
  38133. function FreeCameraInputsManager(camera) {
  38134. return _super.call(this, camera) || this;
  38135. }
  38136. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38137. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38138. return this;
  38139. };
  38140. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38141. if (touchEnabled === void 0) { touchEnabled = true; }
  38142. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38143. return this;
  38144. };
  38145. FreeCameraInputsManager.prototype.addGamepad = function () {
  38146. this.add(new BABYLON.FreeCameraGamepadInput());
  38147. return this;
  38148. };
  38149. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38150. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38151. return this;
  38152. };
  38153. FreeCameraInputsManager.prototype.addTouch = function () {
  38154. this.add(new BABYLON.FreeCameraTouchInput());
  38155. return this;
  38156. };
  38157. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38158. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38159. return this;
  38160. };
  38161. return FreeCameraInputsManager;
  38162. }(BABYLON.CameraInputsManager));
  38163. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38164. })(BABYLON || (BABYLON = {}));
  38165. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38166. var BABYLON;
  38167. (function (BABYLON) {
  38168. var TargetCamera = /** @class */ (function (_super) {
  38169. __extends(TargetCamera, _super);
  38170. function TargetCamera(name, position, scene) {
  38171. var _this = _super.call(this, name, position, scene) || this;
  38172. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38173. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38174. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38175. _this.speed = 2.0;
  38176. _this.noRotationConstraint = false;
  38177. _this.lockedTarget = null;
  38178. _this._currentTarget = BABYLON.Vector3.Zero();
  38179. _this._viewMatrix = BABYLON.Matrix.Zero();
  38180. _this._camMatrix = BABYLON.Matrix.Zero();
  38181. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38182. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38183. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38184. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  38185. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38186. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38187. _this._tempMatrix = BABYLON.Matrix.Zero();
  38188. return _this;
  38189. }
  38190. TargetCamera.prototype.getFrontPosition = function (distance) {
  38191. var direction = this.getTarget().subtract(this.position);
  38192. direction.normalize();
  38193. direction.scaleInPlace(distance);
  38194. return this.globalPosition.add(direction);
  38195. };
  38196. TargetCamera.prototype._getLockedTargetPosition = function () {
  38197. if (!this.lockedTarget) {
  38198. return null;
  38199. }
  38200. if (this.lockedTarget.absolutePosition) {
  38201. this.lockedTarget.computeWorldMatrix();
  38202. }
  38203. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38204. };
  38205. TargetCamera.prototype.storeState = function () {
  38206. this._storedPosition = this.position.clone();
  38207. this._storedRotation = this.rotation.clone();
  38208. if (this.rotationQuaternion) {
  38209. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38210. }
  38211. return _super.prototype.storeState.call(this);
  38212. };
  38213. /**
  38214. * Restored camera state. You must call storeState() first
  38215. */
  38216. TargetCamera.prototype._restoreStateValues = function () {
  38217. if (!_super.prototype._restoreStateValues.call(this)) {
  38218. return false;
  38219. }
  38220. this.position = this._storedPosition.clone();
  38221. this.rotation = this._storedRotation.clone();
  38222. if (this.rotationQuaternion) {
  38223. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38224. }
  38225. this.cameraDirection.copyFromFloats(0, 0, 0);
  38226. this.cameraRotation.copyFromFloats(0, 0);
  38227. return true;
  38228. };
  38229. // Cache
  38230. TargetCamera.prototype._initCache = function () {
  38231. _super.prototype._initCache.call(this);
  38232. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38233. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38234. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38235. };
  38236. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38237. if (!ignoreParentClass) {
  38238. _super.prototype._updateCache.call(this);
  38239. }
  38240. var lockedTargetPosition = this._getLockedTargetPosition();
  38241. if (!lockedTargetPosition) {
  38242. this._cache.lockedTarget = null;
  38243. }
  38244. else {
  38245. if (!this._cache.lockedTarget) {
  38246. this._cache.lockedTarget = lockedTargetPosition.clone();
  38247. }
  38248. else {
  38249. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38250. }
  38251. }
  38252. this._cache.rotation.copyFrom(this.rotation);
  38253. if (this.rotationQuaternion)
  38254. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38255. };
  38256. // Synchronized
  38257. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38258. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38259. return false;
  38260. }
  38261. var lockedTargetPosition = this._getLockedTargetPosition();
  38262. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38263. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38264. };
  38265. // Methods
  38266. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38267. var engine = this.getEngine();
  38268. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38269. };
  38270. // Target
  38271. TargetCamera.prototype.setTarget = function (target) {
  38272. this.upVector.normalize();
  38273. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  38274. this._camMatrix.invert();
  38275. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38276. var vDir = target.subtract(this.position);
  38277. if (vDir.x >= 0.0) {
  38278. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38279. }
  38280. else {
  38281. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38282. }
  38283. this.rotation.z = 0;
  38284. if (isNaN(this.rotation.x)) {
  38285. this.rotation.x = 0;
  38286. }
  38287. if (isNaN(this.rotation.y)) {
  38288. this.rotation.y = 0;
  38289. }
  38290. if (isNaN(this.rotation.z)) {
  38291. this.rotation.z = 0;
  38292. }
  38293. if (this.rotationQuaternion) {
  38294. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38295. }
  38296. };
  38297. /**
  38298. * Return the current target position of the camera. This value is expressed in local space.
  38299. */
  38300. TargetCamera.prototype.getTarget = function () {
  38301. return this._currentTarget;
  38302. };
  38303. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38304. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38305. };
  38306. TargetCamera.prototype._updatePosition = function () {
  38307. if (this.parent) {
  38308. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38309. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38310. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38311. return;
  38312. }
  38313. this.position.addInPlace(this.cameraDirection);
  38314. };
  38315. TargetCamera.prototype._checkInputs = function () {
  38316. var needToMove = this._decideIfNeedsToMove();
  38317. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38318. // Move
  38319. if (needToMove) {
  38320. this._updatePosition();
  38321. }
  38322. // Rotate
  38323. if (needToRotate) {
  38324. this.rotation.x += this.cameraRotation.x;
  38325. this.rotation.y += this.cameraRotation.y;
  38326. //rotate, if quaternion is set and rotation was used
  38327. if (this.rotationQuaternion) {
  38328. var len = this.rotation.lengthSquared();
  38329. if (len) {
  38330. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38331. }
  38332. }
  38333. if (!this.noRotationConstraint) {
  38334. var limit = (Math.PI / 2) * 0.95;
  38335. if (this.rotation.x > limit)
  38336. this.rotation.x = limit;
  38337. if (this.rotation.x < -limit)
  38338. this.rotation.x = -limit;
  38339. }
  38340. }
  38341. // Inertia
  38342. if (needToMove) {
  38343. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38344. this.cameraDirection.x = 0;
  38345. }
  38346. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38347. this.cameraDirection.y = 0;
  38348. }
  38349. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38350. this.cameraDirection.z = 0;
  38351. }
  38352. this.cameraDirection.scaleInPlace(this.inertia);
  38353. }
  38354. if (needToRotate) {
  38355. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38356. this.cameraRotation.x = 0;
  38357. }
  38358. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38359. this.cameraRotation.y = 0;
  38360. }
  38361. this.cameraRotation.scaleInPlace(this.inertia);
  38362. }
  38363. _super.prototype._checkInputs.call(this);
  38364. };
  38365. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38366. if (this.rotationQuaternion) {
  38367. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38368. }
  38369. else {
  38370. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38371. }
  38372. //update the up vector!
  38373. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  38374. };
  38375. TargetCamera.prototype._getViewMatrix = function () {
  38376. if (!this.lockedTarget) {
  38377. // Compute
  38378. this._updateCameraRotationMatrix();
  38379. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38380. // Computing target and final matrix
  38381. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38382. }
  38383. else {
  38384. var targetPosition = this._getLockedTargetPosition();
  38385. if (targetPosition) {
  38386. this._currentTarget.copyFrom(targetPosition);
  38387. }
  38388. }
  38389. if (this.getScene().useRightHandedSystem) {
  38390. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38391. }
  38392. else {
  38393. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38394. }
  38395. return this._viewMatrix;
  38396. };
  38397. /**
  38398. * @override
  38399. * Override Camera.createRigCamera
  38400. */
  38401. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38402. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38403. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38404. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38405. if (!this.rotationQuaternion) {
  38406. this.rotationQuaternion = new BABYLON.Quaternion();
  38407. }
  38408. rigCamera._cameraRigParams = {};
  38409. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38410. }
  38411. return rigCamera;
  38412. }
  38413. return null;
  38414. };
  38415. /**
  38416. * @override
  38417. * Override Camera._updateRigCameras
  38418. */
  38419. TargetCamera.prototype._updateRigCameras = function () {
  38420. var camLeft = this._rigCameras[0];
  38421. var camRight = this._rigCameras[1];
  38422. switch (this.cameraRigMode) {
  38423. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38424. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38425. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38426. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38427. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38428. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38429. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38430. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38431. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38432. camLeft.setTarget(this.getTarget());
  38433. camRight.setTarget(this.getTarget());
  38434. break;
  38435. case BABYLON.Camera.RIG_MODE_VR:
  38436. if (camLeft.rotationQuaternion) {
  38437. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38438. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38439. }
  38440. else {
  38441. camLeft.rotation.copyFrom(this.rotation);
  38442. camRight.rotation.copyFrom(this.rotation);
  38443. }
  38444. camLeft.position.copyFrom(this.position);
  38445. camRight.position.copyFrom(this.position);
  38446. break;
  38447. }
  38448. _super.prototype._updateRigCameras.call(this);
  38449. };
  38450. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38451. if (!this._rigCamTransformMatrix) {
  38452. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38453. }
  38454. var target = this.getTarget();
  38455. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38456. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38457. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38458. };
  38459. TargetCamera.prototype.getClassName = function () {
  38460. return "TargetCamera";
  38461. };
  38462. __decorate([
  38463. BABYLON.serializeAsVector3()
  38464. ], TargetCamera.prototype, "rotation", void 0);
  38465. __decorate([
  38466. BABYLON.serialize()
  38467. ], TargetCamera.prototype, "speed", void 0);
  38468. __decorate([
  38469. BABYLON.serializeAsMeshReference("lockedTargetId")
  38470. ], TargetCamera.prototype, "lockedTarget", void 0);
  38471. return TargetCamera;
  38472. }(BABYLON.Camera));
  38473. BABYLON.TargetCamera = TargetCamera;
  38474. })(BABYLON || (BABYLON = {}));
  38475. //# sourceMappingURL=babylon.targetCamera.js.map
  38476. var BABYLON;
  38477. (function (BABYLON) {
  38478. var FreeCamera = /** @class */ (function (_super) {
  38479. __extends(FreeCamera, _super);
  38480. function FreeCamera(name, position, scene) {
  38481. var _this = _super.call(this, name, position, scene) || this;
  38482. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38483. _this.checkCollisions = false;
  38484. _this.applyGravity = false;
  38485. _this._needMoveForGravity = false;
  38486. _this._oldPosition = BABYLON.Vector3.Zero();
  38487. _this._diffPosition = BABYLON.Vector3.Zero();
  38488. _this._newPosition = BABYLON.Vector3.Zero();
  38489. // Collisions
  38490. _this._collisionMask = -1;
  38491. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38492. if (collidedMesh === void 0) { collidedMesh = null; }
  38493. //TODO move this to the collision coordinator!
  38494. if (_this.getScene().workerCollisions)
  38495. newPosition.multiplyInPlace(_this._collider.radius);
  38496. var updatePosition = function (newPos) {
  38497. _this._newPosition.copyFrom(newPos);
  38498. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38499. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38500. _this.position.addInPlace(_this._diffPosition);
  38501. if (_this.onCollide && collidedMesh) {
  38502. _this.onCollide(collidedMesh);
  38503. }
  38504. }
  38505. };
  38506. updatePosition(newPosition);
  38507. };
  38508. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38509. _this.inputs.addKeyboard().addMouse();
  38510. return _this;
  38511. }
  38512. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38513. //-- begin properties for backward compatibility for inputs
  38514. get: function () {
  38515. var mouse = this.inputs.attached["mouse"];
  38516. if (mouse)
  38517. return mouse.angularSensibility;
  38518. return 0;
  38519. },
  38520. set: function (value) {
  38521. var mouse = this.inputs.attached["mouse"];
  38522. if (mouse)
  38523. mouse.angularSensibility = value;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38529. get: function () {
  38530. var keyboard = this.inputs.attached["keyboard"];
  38531. if (keyboard)
  38532. return keyboard.keysUp;
  38533. return [];
  38534. },
  38535. set: function (value) {
  38536. var keyboard = this.inputs.attached["keyboard"];
  38537. if (keyboard)
  38538. keyboard.keysUp = value;
  38539. },
  38540. enumerable: true,
  38541. configurable: true
  38542. });
  38543. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38544. get: function () {
  38545. var keyboard = this.inputs.attached["keyboard"];
  38546. if (keyboard)
  38547. return keyboard.keysDown;
  38548. return [];
  38549. },
  38550. set: function (value) {
  38551. var keyboard = this.inputs.attached["keyboard"];
  38552. if (keyboard)
  38553. keyboard.keysDown = value;
  38554. },
  38555. enumerable: true,
  38556. configurable: true
  38557. });
  38558. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38559. get: function () {
  38560. var keyboard = this.inputs.attached["keyboard"];
  38561. if (keyboard)
  38562. return keyboard.keysLeft;
  38563. return [];
  38564. },
  38565. set: function (value) {
  38566. var keyboard = this.inputs.attached["keyboard"];
  38567. if (keyboard)
  38568. keyboard.keysLeft = value;
  38569. },
  38570. enumerable: true,
  38571. configurable: true
  38572. });
  38573. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38574. get: function () {
  38575. var keyboard = this.inputs.attached["keyboard"];
  38576. if (keyboard)
  38577. return keyboard.keysRight;
  38578. return [];
  38579. },
  38580. set: function (value) {
  38581. var keyboard = this.inputs.attached["keyboard"];
  38582. if (keyboard)
  38583. keyboard.keysRight = value;
  38584. },
  38585. enumerable: true,
  38586. configurable: true
  38587. });
  38588. // Controls
  38589. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38590. this.inputs.attachElement(element, noPreventDefault);
  38591. };
  38592. FreeCamera.prototype.detachControl = function (element) {
  38593. this.inputs.detachElement(element);
  38594. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38595. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38596. };
  38597. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38598. get: function () {
  38599. return this._collisionMask;
  38600. },
  38601. set: function (mask) {
  38602. this._collisionMask = !isNaN(mask) ? mask : -1;
  38603. },
  38604. enumerable: true,
  38605. configurable: true
  38606. });
  38607. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38608. var globalPosition;
  38609. if (this.parent) {
  38610. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38611. }
  38612. else {
  38613. globalPosition = this.position;
  38614. }
  38615. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38616. if (!this._collider) {
  38617. this._collider = new BABYLON.Collider();
  38618. }
  38619. this._collider.radius = this.ellipsoid;
  38620. this._collider.collisionMask = this._collisionMask;
  38621. //no need for clone, as long as gravity is not on.
  38622. var actualDisplacement = displacement;
  38623. //add gravity to the direction to prevent the dual-collision checking
  38624. if (this.applyGravity) {
  38625. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38626. actualDisplacement = displacement.add(this.getScene().gravity);
  38627. }
  38628. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38629. };
  38630. FreeCamera.prototype._checkInputs = function () {
  38631. if (!this._localDirection) {
  38632. this._localDirection = BABYLON.Vector3.Zero();
  38633. this._transformedDirection = BABYLON.Vector3.Zero();
  38634. }
  38635. this.inputs.checkInputs();
  38636. _super.prototype._checkInputs.call(this);
  38637. };
  38638. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38639. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38640. };
  38641. FreeCamera.prototype._updatePosition = function () {
  38642. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38643. this._collideWithWorld(this.cameraDirection);
  38644. }
  38645. else {
  38646. _super.prototype._updatePosition.call(this);
  38647. }
  38648. };
  38649. FreeCamera.prototype.dispose = function () {
  38650. this.inputs.clear();
  38651. _super.prototype.dispose.call(this);
  38652. };
  38653. FreeCamera.prototype.getClassName = function () {
  38654. return "FreeCamera";
  38655. };
  38656. __decorate([
  38657. BABYLON.serializeAsVector3()
  38658. ], FreeCamera.prototype, "ellipsoid", void 0);
  38659. __decorate([
  38660. BABYLON.serialize()
  38661. ], FreeCamera.prototype, "checkCollisions", void 0);
  38662. __decorate([
  38663. BABYLON.serialize()
  38664. ], FreeCamera.prototype, "applyGravity", void 0);
  38665. return FreeCamera;
  38666. }(BABYLON.TargetCamera));
  38667. BABYLON.FreeCamera = FreeCamera;
  38668. })(BABYLON || (BABYLON = {}));
  38669. //# sourceMappingURL=babylon.freeCamera.js.map
  38670. var BABYLON;
  38671. (function (BABYLON) {
  38672. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38673. function ArcRotateCameraKeyboardMoveInput() {
  38674. this._keys = new Array();
  38675. this.keysUp = [38];
  38676. this.keysDown = [40];
  38677. this.keysLeft = [37];
  38678. this.keysRight = [39];
  38679. this.keysReset = [220];
  38680. this.panningSensibility = 50.0;
  38681. this.zoomingSensibility = 25.0;
  38682. this.useAltToZoom = true;
  38683. }
  38684. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38685. var _this = this;
  38686. if (this._onCanvasBlurObserver) {
  38687. return;
  38688. }
  38689. this._scene = this.camera.getScene();
  38690. this._engine = this._scene.getEngine();
  38691. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38692. _this._keys = [];
  38693. });
  38694. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38695. var evt = info.event;
  38696. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38697. _this._ctrlPressed = evt.ctrlKey;
  38698. _this._altPressed = evt.altKey;
  38699. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38700. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38701. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38702. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38703. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38704. var index = _this._keys.indexOf(evt.keyCode);
  38705. if (index === -1) {
  38706. _this._keys.push(evt.keyCode);
  38707. }
  38708. if (evt.preventDefault) {
  38709. if (!noPreventDefault) {
  38710. evt.preventDefault();
  38711. }
  38712. }
  38713. }
  38714. }
  38715. else {
  38716. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38717. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38718. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38719. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38720. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38721. var index = _this._keys.indexOf(evt.keyCode);
  38722. if (index >= 0) {
  38723. _this._keys.splice(index, 1);
  38724. }
  38725. if (evt.preventDefault) {
  38726. if (!noPreventDefault) {
  38727. evt.preventDefault();
  38728. }
  38729. }
  38730. }
  38731. }
  38732. });
  38733. };
  38734. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38735. if (this._scene) {
  38736. if (this._onKeyboardObserver) {
  38737. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38738. }
  38739. if (this._onCanvasBlurObserver) {
  38740. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38741. }
  38742. this._onKeyboardObserver = null;
  38743. this._onCanvasBlurObserver = null;
  38744. }
  38745. this._keys = [];
  38746. };
  38747. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38748. if (this._onKeyboardObserver) {
  38749. var camera = this.camera;
  38750. for (var index = 0; index < this._keys.length; index++) {
  38751. var keyCode = this._keys[index];
  38752. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38753. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38754. camera.inertialPanningX -= 1 / this.panningSensibility;
  38755. }
  38756. else {
  38757. camera.inertialAlphaOffset -= 0.01;
  38758. }
  38759. }
  38760. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38761. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38762. camera.inertialPanningY += 1 / this.panningSensibility;
  38763. }
  38764. else if (this._altPressed && this.useAltToZoom) {
  38765. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38766. }
  38767. else {
  38768. camera.inertialBetaOffset -= 0.01;
  38769. }
  38770. }
  38771. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38772. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38773. camera.inertialPanningX += 1 / this.panningSensibility;
  38774. }
  38775. else {
  38776. camera.inertialAlphaOffset += 0.01;
  38777. }
  38778. }
  38779. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38780. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38781. camera.inertialPanningY -= 1 / this.panningSensibility;
  38782. }
  38783. else if (this._altPressed && this.useAltToZoom) {
  38784. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38785. }
  38786. else {
  38787. camera.inertialBetaOffset += 0.01;
  38788. }
  38789. }
  38790. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38791. camera.restoreState();
  38792. }
  38793. }
  38794. }
  38795. };
  38796. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38797. return "ArcRotateCameraKeyboardMoveInput";
  38798. };
  38799. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38800. return "keyboard";
  38801. };
  38802. __decorate([
  38803. BABYLON.serialize()
  38804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38805. __decorate([
  38806. BABYLON.serialize()
  38807. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38808. __decorate([
  38809. BABYLON.serialize()
  38810. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38811. __decorate([
  38812. BABYLON.serialize()
  38813. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38814. __decorate([
  38815. BABYLON.serialize()
  38816. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38817. __decorate([
  38818. BABYLON.serialize()
  38819. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38820. __decorate([
  38821. BABYLON.serialize()
  38822. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38823. __decorate([
  38824. BABYLON.serialize()
  38825. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38826. return ArcRotateCameraKeyboardMoveInput;
  38827. }());
  38828. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38829. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38830. })(BABYLON || (BABYLON = {}));
  38831. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38832. var BABYLON;
  38833. (function (BABYLON) {
  38834. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38835. function ArcRotateCameraMouseWheelInput() {
  38836. this.wheelPrecision = 3.0;
  38837. /**
  38838. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38839. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38840. */
  38841. this.wheelDeltaPercentage = 0;
  38842. }
  38843. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38844. var _this = this;
  38845. this._wheel = function (p, s) {
  38846. //sanity check - this should be a PointerWheel event.
  38847. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38848. return;
  38849. var event = p.event;
  38850. var delta = 0;
  38851. if (event.wheelDelta) {
  38852. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38853. }
  38854. else if (event.detail) {
  38855. delta = -event.detail / _this.wheelPrecision;
  38856. }
  38857. if (delta)
  38858. _this.camera.inertialRadiusOffset += delta;
  38859. if (event.preventDefault) {
  38860. if (!noPreventDefault) {
  38861. event.preventDefault();
  38862. }
  38863. }
  38864. };
  38865. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38866. };
  38867. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38868. if (this._observer && element) {
  38869. this.camera.getScene().onPointerObservable.remove(this._observer);
  38870. this._observer = null;
  38871. this._wheel = null;
  38872. }
  38873. };
  38874. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38875. return "ArcRotateCameraMouseWheelInput";
  38876. };
  38877. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38878. return "mousewheel";
  38879. };
  38880. __decorate([
  38881. BABYLON.serialize()
  38882. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38883. __decorate([
  38884. BABYLON.serialize()
  38885. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38886. return ArcRotateCameraMouseWheelInput;
  38887. }());
  38888. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38889. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38890. })(BABYLON || (BABYLON = {}));
  38891. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38892. var BABYLON;
  38893. (function (BABYLON) {
  38894. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38895. function ArcRotateCameraPointersInput() {
  38896. this.buttons = [0, 1, 2];
  38897. this.angularSensibilityX = 1000.0;
  38898. this.angularSensibilityY = 1000.0;
  38899. this.pinchPrecision = 12.0;
  38900. /**
  38901. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38902. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38903. */
  38904. this.pinchDeltaPercentage = 0;
  38905. this.panningSensibility = 1000.0;
  38906. this.multiTouchPanning = true;
  38907. this.multiTouchPanAndZoom = true;
  38908. this._isPanClick = false;
  38909. this.pinchInwards = true;
  38910. }
  38911. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38912. var _this = this;
  38913. var engine = this.camera.getEngine();
  38914. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38915. var pointA = null;
  38916. var pointB = null;
  38917. var previousPinchSquaredDistance = 0;
  38918. var initialDistance = 0;
  38919. var twoFingerActivityCount = 0;
  38920. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38921. this._pointerInput = function (p, s) {
  38922. var evt = p.event;
  38923. var isTouch = p.event.pointerType === "touch";
  38924. if (engine.isInVRExclusivePointerMode) {
  38925. return;
  38926. }
  38927. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38928. return;
  38929. }
  38930. var srcElement = (evt.srcElement || evt.target);
  38931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38932. try {
  38933. srcElement.setPointerCapture(evt.pointerId);
  38934. }
  38935. catch (e) {
  38936. //Nothing to do with the error. Execution will continue.
  38937. }
  38938. // Manage panning with pan button click
  38939. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38940. // manage pointers
  38941. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38942. if (pointA === null) {
  38943. pointA = cacheSoloPointer;
  38944. }
  38945. else if (pointB === null) {
  38946. pointB = cacheSoloPointer;
  38947. }
  38948. if (!noPreventDefault) {
  38949. evt.preventDefault();
  38950. element.focus();
  38951. }
  38952. }
  38953. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38954. _this.camera.restoreState();
  38955. }
  38956. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38957. try {
  38958. srcElement.releasePointerCapture(evt.pointerId);
  38959. }
  38960. catch (e) {
  38961. //Nothing to do with the error.
  38962. }
  38963. cacheSoloPointer = null;
  38964. previousPinchSquaredDistance = 0;
  38965. previousMultiTouchPanPosition.isPaning = false;
  38966. previousMultiTouchPanPosition.isPinching = false;
  38967. twoFingerActivityCount = 0;
  38968. initialDistance = 0;
  38969. if (!isTouch) {
  38970. pointB = null; // Mouse and pen are mono pointer
  38971. }
  38972. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38973. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38974. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38975. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38976. if (engine.badOS) {
  38977. pointA = pointB = null;
  38978. }
  38979. else {
  38980. //only remove the impacted pointer in case of multitouch allowing on most
  38981. //platforms switching from rotate to zoom and pan seamlessly.
  38982. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38983. pointA = pointB;
  38984. pointB = null;
  38985. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38986. }
  38987. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38988. pointB = null;
  38989. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38990. }
  38991. else {
  38992. pointA = pointB = null;
  38993. }
  38994. }
  38995. if (!noPreventDefault) {
  38996. evt.preventDefault();
  38997. }
  38998. }
  38999. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39000. if (!noPreventDefault) {
  39001. evt.preventDefault();
  39002. }
  39003. // One button down
  39004. if (pointA && pointB === null && cacheSoloPointer) {
  39005. if (_this.panningSensibility !== 0 &&
  39006. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39007. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39008. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39009. }
  39010. else {
  39011. var offsetX = evt.clientX - cacheSoloPointer.x;
  39012. var offsetY = evt.clientY - cacheSoloPointer.y;
  39013. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39014. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39015. }
  39016. cacheSoloPointer.x = evt.clientX;
  39017. cacheSoloPointer.y = evt.clientY;
  39018. }
  39019. else if (pointA && pointB) {
  39020. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39021. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39022. ed.x = evt.clientX;
  39023. ed.y = evt.clientY;
  39024. var direction = _this.pinchInwards ? 1 : -1;
  39025. var distX = pointA.x - pointB.x;
  39026. var distY = pointA.y - pointB.y;
  39027. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39028. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39029. if (previousPinchSquaredDistance === 0) {
  39030. initialDistance = pinchDistance;
  39031. previousPinchSquaredDistance = pinchSquaredDistance;
  39032. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39033. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39034. return;
  39035. }
  39036. if (_this.multiTouchPanAndZoom) {
  39037. if (_this.pinchDeltaPercentage) {
  39038. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39039. }
  39040. else {
  39041. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39042. (_this.pinchPrecision *
  39043. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39044. direction);
  39045. }
  39046. if (_this.panningSensibility !== 0) {
  39047. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39048. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39049. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39050. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39051. previousMultiTouchPanPosition.x = pointersCenterX;
  39052. previousMultiTouchPanPosition.y = pointersCenterY;
  39053. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39054. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39055. }
  39056. }
  39057. else {
  39058. twoFingerActivityCount++;
  39059. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39060. if (_this.pinchDeltaPercentage) {
  39061. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39062. }
  39063. else {
  39064. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39065. (_this.pinchPrecision *
  39066. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39067. direction);
  39068. }
  39069. previousMultiTouchPanPosition.isPaning = false;
  39070. previousMultiTouchPanPosition.isPinching = true;
  39071. }
  39072. else {
  39073. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39074. if (!previousMultiTouchPanPosition.isPaning) {
  39075. previousMultiTouchPanPosition.isPaning = true;
  39076. previousMultiTouchPanPosition.isPinching = false;
  39077. previousMultiTouchPanPosition.x = ed.x;
  39078. previousMultiTouchPanPosition.y = ed.y;
  39079. return;
  39080. }
  39081. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39082. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39083. }
  39084. }
  39085. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39086. previousMultiTouchPanPosition.x = ed.x;
  39087. previousMultiTouchPanPosition.y = ed.y;
  39088. }
  39089. }
  39090. previousPinchSquaredDistance = pinchSquaredDistance;
  39091. }
  39092. }
  39093. };
  39094. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39095. this._onContextMenu = function (evt) {
  39096. evt.preventDefault();
  39097. };
  39098. if (!this.camera._useCtrlForPanning) {
  39099. element.addEventListener("contextmenu", this._onContextMenu, false);
  39100. }
  39101. this._onLostFocus = function () {
  39102. //this._keys = [];
  39103. pointA = pointB = null;
  39104. previousPinchSquaredDistance = 0;
  39105. previousMultiTouchPanPosition.isPaning = false;
  39106. previousMultiTouchPanPosition.isPinching = false;
  39107. twoFingerActivityCount = 0;
  39108. cacheSoloPointer = null;
  39109. initialDistance = 0;
  39110. };
  39111. this._onMouseMove = function (evt) {
  39112. if (!engine.isPointerLock) {
  39113. return;
  39114. }
  39115. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39116. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39117. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39118. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39119. if (!noPreventDefault) {
  39120. evt.preventDefault();
  39121. }
  39122. };
  39123. this._onGestureStart = function (e) {
  39124. if (window.MSGesture === undefined) {
  39125. return;
  39126. }
  39127. if (!_this._MSGestureHandler) {
  39128. _this._MSGestureHandler = new MSGesture();
  39129. _this._MSGestureHandler.target = element;
  39130. }
  39131. _this._MSGestureHandler.addPointer(e.pointerId);
  39132. };
  39133. this._onGesture = function (e) {
  39134. _this.camera.radius *= e.scale;
  39135. if (e.preventDefault) {
  39136. if (!noPreventDefault) {
  39137. e.stopPropagation();
  39138. e.preventDefault();
  39139. }
  39140. }
  39141. };
  39142. element.addEventListener("mousemove", this._onMouseMove, false);
  39143. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39144. element.addEventListener("MSGestureChange", this._onGesture, false);
  39145. BABYLON.Tools.RegisterTopRootEvents([
  39146. { name: "blur", handler: this._onLostFocus }
  39147. ]);
  39148. };
  39149. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39150. if (this._onLostFocus) {
  39151. BABYLON.Tools.UnregisterTopRootEvents([
  39152. { name: "blur", handler: this._onLostFocus }
  39153. ]);
  39154. }
  39155. if (element && this._observer) {
  39156. this.camera.getScene().onPointerObservable.remove(this._observer);
  39157. this._observer = null;
  39158. if (this._onContextMenu) {
  39159. element.removeEventListener("contextmenu", this._onContextMenu);
  39160. }
  39161. if (this._onMouseMove) {
  39162. element.removeEventListener("mousemove", this._onMouseMove);
  39163. }
  39164. if (this._onGestureStart) {
  39165. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39166. }
  39167. if (this._onGesture) {
  39168. element.removeEventListener("MSGestureChange", this._onGesture);
  39169. }
  39170. this._isPanClick = false;
  39171. this.pinchInwards = true;
  39172. this._onMouseMove = null;
  39173. this._onGestureStart = null;
  39174. this._onGesture = null;
  39175. this._MSGestureHandler = null;
  39176. this._onLostFocus = null;
  39177. this._onContextMenu = null;
  39178. }
  39179. };
  39180. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39181. return "ArcRotateCameraPointersInput";
  39182. };
  39183. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39184. return "pointers";
  39185. };
  39186. __decorate([
  39187. BABYLON.serialize()
  39188. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39189. __decorate([
  39190. BABYLON.serialize()
  39191. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39192. __decorate([
  39193. BABYLON.serialize()
  39194. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39195. __decorate([
  39196. BABYLON.serialize()
  39197. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39198. __decorate([
  39199. BABYLON.serialize()
  39200. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39201. __decorate([
  39202. BABYLON.serialize()
  39203. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39204. __decorate([
  39205. BABYLON.serialize()
  39206. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39207. __decorate([
  39208. BABYLON.serialize()
  39209. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39210. return ArcRotateCameraPointersInput;
  39211. }());
  39212. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39213. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39214. })(BABYLON || (BABYLON = {}));
  39215. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39216. var BABYLON;
  39217. (function (BABYLON) {
  39218. var ArcRotateCamera = /** @class */ (function (_super) {
  39219. __extends(ArcRotateCamera, _super);
  39220. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39221. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39222. _this.inertialAlphaOffset = 0;
  39223. _this.inertialBetaOffset = 0;
  39224. _this.inertialRadiusOffset = 0;
  39225. _this.lowerAlphaLimit = null;
  39226. _this.upperAlphaLimit = null;
  39227. _this.lowerBetaLimit = 0.01;
  39228. _this.upperBetaLimit = Math.PI;
  39229. _this.lowerRadiusLimit = null;
  39230. _this.upperRadiusLimit = null;
  39231. _this.inertialPanningX = 0;
  39232. _this.inertialPanningY = 0;
  39233. _this.pinchToPanMaxDistance = 20;
  39234. _this.panningDistanceLimit = null;
  39235. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39236. _this.panningInertia = 0.9;
  39237. //-- end properties for backward compatibility for inputs
  39238. _this.zoomOnFactor = 1;
  39239. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39240. _this.allowUpsideDown = true;
  39241. _this._viewMatrix = new BABYLON.Matrix();
  39242. // Panning
  39243. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39244. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39245. _this.checkCollisions = false;
  39246. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39247. _this._previousPosition = BABYLON.Vector3.Zero();
  39248. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39249. _this._newPosition = BABYLON.Vector3.Zero();
  39250. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39251. if (collidedMesh === void 0) { collidedMesh = null; }
  39252. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39253. newPosition.multiplyInPlace(_this._collider.radius);
  39254. }
  39255. if (!collidedMesh) {
  39256. _this._previousPosition.copyFrom(_this.position);
  39257. }
  39258. else {
  39259. _this.setPosition(newPosition);
  39260. if (_this.onCollide) {
  39261. _this.onCollide(collidedMesh);
  39262. }
  39263. }
  39264. // Recompute because of constraints
  39265. var cosa = Math.cos(_this.alpha);
  39266. var sina = Math.sin(_this.alpha);
  39267. var cosb = Math.cos(_this.beta);
  39268. var sinb = Math.sin(_this.beta);
  39269. if (sinb === 0) {
  39270. sinb = 0.0001;
  39271. }
  39272. var target = _this._getTargetPosition();
  39273. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39274. _this.position.copyFrom(_this._newPosition);
  39275. var up = _this.upVector;
  39276. if (_this.allowUpsideDown && _this.beta < 0) {
  39277. up = up.clone();
  39278. up = up.negate();
  39279. }
  39280. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39281. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39282. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39283. _this._collisionTriggered = false;
  39284. };
  39285. _this._target = BABYLON.Vector3.Zero();
  39286. if (target) {
  39287. _this.setTarget(target);
  39288. }
  39289. _this.alpha = alpha;
  39290. _this.beta = beta;
  39291. _this.radius = radius;
  39292. _this.getViewMatrix();
  39293. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39294. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39295. return _this;
  39296. }
  39297. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39298. get: function () {
  39299. return this._target;
  39300. },
  39301. set: function (value) {
  39302. this.setTarget(value);
  39303. },
  39304. enumerable: true,
  39305. configurable: true
  39306. });
  39307. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39308. //-- begin properties for backward compatibility for inputs
  39309. get: function () {
  39310. var pointers = this.inputs.attached["pointers"];
  39311. if (pointers)
  39312. return pointers.angularSensibilityX;
  39313. return 0;
  39314. },
  39315. set: function (value) {
  39316. var pointers = this.inputs.attached["pointers"];
  39317. if (pointers) {
  39318. pointers.angularSensibilityX = value;
  39319. }
  39320. },
  39321. enumerable: true,
  39322. configurable: true
  39323. });
  39324. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39325. get: function () {
  39326. var pointers = this.inputs.attached["pointers"];
  39327. if (pointers)
  39328. return pointers.angularSensibilityY;
  39329. return 0;
  39330. },
  39331. set: function (value) {
  39332. var pointers = this.inputs.attached["pointers"];
  39333. if (pointers) {
  39334. pointers.angularSensibilityY = value;
  39335. }
  39336. },
  39337. enumerable: true,
  39338. configurable: true
  39339. });
  39340. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39341. get: function () {
  39342. var pointers = this.inputs.attached["pointers"];
  39343. if (pointers)
  39344. return pointers.pinchPrecision;
  39345. return 0;
  39346. },
  39347. set: function (value) {
  39348. var pointers = this.inputs.attached["pointers"];
  39349. if (pointers) {
  39350. pointers.pinchPrecision = value;
  39351. }
  39352. },
  39353. enumerable: true,
  39354. configurable: true
  39355. });
  39356. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39357. get: function () {
  39358. var pointers = this.inputs.attached["pointers"];
  39359. if (pointers)
  39360. return pointers.pinchDeltaPercentage;
  39361. return 0;
  39362. },
  39363. set: function (value) {
  39364. var pointers = this.inputs.attached["pointers"];
  39365. if (pointers) {
  39366. pointers.pinchDeltaPercentage = value;
  39367. }
  39368. },
  39369. enumerable: true,
  39370. configurable: true
  39371. });
  39372. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39373. get: function () {
  39374. var pointers = this.inputs.attached["pointers"];
  39375. if (pointers)
  39376. return pointers.panningSensibility;
  39377. return 0;
  39378. },
  39379. set: function (value) {
  39380. var pointers = this.inputs.attached["pointers"];
  39381. if (pointers) {
  39382. pointers.panningSensibility = value;
  39383. }
  39384. },
  39385. enumerable: true,
  39386. configurable: true
  39387. });
  39388. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39389. get: function () {
  39390. var keyboard = this.inputs.attached["keyboard"];
  39391. if (keyboard)
  39392. return keyboard.keysUp;
  39393. return [];
  39394. },
  39395. set: function (value) {
  39396. var keyboard = this.inputs.attached["keyboard"];
  39397. if (keyboard)
  39398. keyboard.keysUp = value;
  39399. },
  39400. enumerable: true,
  39401. configurable: true
  39402. });
  39403. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39404. get: function () {
  39405. var keyboard = this.inputs.attached["keyboard"];
  39406. if (keyboard)
  39407. return keyboard.keysDown;
  39408. return [];
  39409. },
  39410. set: function (value) {
  39411. var keyboard = this.inputs.attached["keyboard"];
  39412. if (keyboard)
  39413. keyboard.keysDown = value;
  39414. },
  39415. enumerable: true,
  39416. configurable: true
  39417. });
  39418. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39419. get: function () {
  39420. var keyboard = this.inputs.attached["keyboard"];
  39421. if (keyboard)
  39422. return keyboard.keysLeft;
  39423. return [];
  39424. },
  39425. set: function (value) {
  39426. var keyboard = this.inputs.attached["keyboard"];
  39427. if (keyboard)
  39428. keyboard.keysLeft = value;
  39429. },
  39430. enumerable: true,
  39431. configurable: true
  39432. });
  39433. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39434. get: function () {
  39435. var keyboard = this.inputs.attached["keyboard"];
  39436. if (keyboard)
  39437. return keyboard.keysRight;
  39438. return [];
  39439. },
  39440. set: function (value) {
  39441. var keyboard = this.inputs.attached["keyboard"];
  39442. if (keyboard)
  39443. keyboard.keysRight = value;
  39444. },
  39445. enumerable: true,
  39446. configurable: true
  39447. });
  39448. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39449. get: function () {
  39450. var mousewheel = this.inputs.attached["mousewheel"];
  39451. if (mousewheel)
  39452. return mousewheel.wheelPrecision;
  39453. return 0;
  39454. },
  39455. set: function (value) {
  39456. var mousewheel = this.inputs.attached["mousewheel"];
  39457. if (mousewheel)
  39458. mousewheel.wheelPrecision = value;
  39459. },
  39460. enumerable: true,
  39461. configurable: true
  39462. });
  39463. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39464. get: function () {
  39465. var mousewheel = this.inputs.attached["mousewheel"];
  39466. if (mousewheel)
  39467. return mousewheel.wheelDeltaPercentage;
  39468. return 0;
  39469. },
  39470. set: function (value) {
  39471. var mousewheel = this.inputs.attached["mousewheel"];
  39472. if (mousewheel)
  39473. mousewheel.wheelDeltaPercentage = value;
  39474. },
  39475. enumerable: true,
  39476. configurable: true
  39477. });
  39478. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39479. get: function () {
  39480. return this._bouncingBehavior;
  39481. },
  39482. enumerable: true,
  39483. configurable: true
  39484. });
  39485. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39486. get: function () {
  39487. return this._bouncingBehavior != null;
  39488. },
  39489. set: function (value) {
  39490. if (value === this.useBouncingBehavior) {
  39491. return;
  39492. }
  39493. if (value) {
  39494. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39495. this.addBehavior(this._bouncingBehavior);
  39496. }
  39497. else if (this._bouncingBehavior) {
  39498. this.removeBehavior(this._bouncingBehavior);
  39499. this._bouncingBehavior = null;
  39500. }
  39501. },
  39502. enumerable: true,
  39503. configurable: true
  39504. });
  39505. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39506. get: function () {
  39507. return this._framingBehavior;
  39508. },
  39509. enumerable: true,
  39510. configurable: true
  39511. });
  39512. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39513. get: function () {
  39514. return this._framingBehavior != null;
  39515. },
  39516. set: function (value) {
  39517. if (value === this.useFramingBehavior) {
  39518. return;
  39519. }
  39520. if (value) {
  39521. this._framingBehavior = new BABYLON.FramingBehavior();
  39522. this.addBehavior(this._framingBehavior);
  39523. }
  39524. else if (this._framingBehavior) {
  39525. this.removeBehavior(this._framingBehavior);
  39526. this._framingBehavior = null;
  39527. }
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39533. get: function () {
  39534. return this._autoRotationBehavior;
  39535. },
  39536. enumerable: true,
  39537. configurable: true
  39538. });
  39539. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39540. get: function () {
  39541. return this._autoRotationBehavior != null;
  39542. },
  39543. set: function (value) {
  39544. if (value === this.useAutoRotationBehavior) {
  39545. return;
  39546. }
  39547. if (value) {
  39548. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39549. this.addBehavior(this._autoRotationBehavior);
  39550. }
  39551. else if (this._autoRotationBehavior) {
  39552. this.removeBehavior(this._autoRotationBehavior);
  39553. this._autoRotationBehavior = null;
  39554. }
  39555. },
  39556. enumerable: true,
  39557. configurable: true
  39558. });
  39559. // Cache
  39560. ArcRotateCamera.prototype._initCache = function () {
  39561. _super.prototype._initCache.call(this);
  39562. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39563. this._cache.alpha = undefined;
  39564. this._cache.beta = undefined;
  39565. this._cache.radius = undefined;
  39566. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39567. };
  39568. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39569. if (!ignoreParentClass) {
  39570. _super.prototype._updateCache.call(this);
  39571. }
  39572. this._cache._target.copyFrom(this._getTargetPosition());
  39573. this._cache.alpha = this.alpha;
  39574. this._cache.beta = this.beta;
  39575. this._cache.radius = this.radius;
  39576. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39577. };
  39578. ArcRotateCamera.prototype._getTargetPosition = function () {
  39579. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39580. var pos = this._targetHost.getAbsolutePosition();
  39581. if (this._targetBoundingCenter) {
  39582. pos.addToRef(this._targetBoundingCenter, this._target);
  39583. }
  39584. else {
  39585. this._target.copyFrom(pos);
  39586. }
  39587. }
  39588. var lockedTargetPosition = this._getLockedTargetPosition();
  39589. if (lockedTargetPosition) {
  39590. return lockedTargetPosition;
  39591. }
  39592. return this._target;
  39593. };
  39594. ArcRotateCamera.prototype.storeState = function () {
  39595. this._storedAlpha = this.alpha;
  39596. this._storedBeta = this.beta;
  39597. this._storedRadius = this.radius;
  39598. this._storedTarget = this._getTargetPosition().clone();
  39599. return _super.prototype.storeState.call(this);
  39600. };
  39601. /**
  39602. * Restored camera state. You must call storeState() first
  39603. */
  39604. ArcRotateCamera.prototype._restoreStateValues = function () {
  39605. if (!_super.prototype._restoreStateValues.call(this)) {
  39606. return false;
  39607. }
  39608. this.alpha = this._storedAlpha;
  39609. this.beta = this._storedBeta;
  39610. this.radius = this._storedRadius;
  39611. this.setTarget(this._storedTarget.clone());
  39612. this.inertialAlphaOffset = 0;
  39613. this.inertialBetaOffset = 0;
  39614. this.inertialRadiusOffset = 0;
  39615. this.inertialPanningX = 0;
  39616. this.inertialPanningY = 0;
  39617. return true;
  39618. };
  39619. // Synchronized
  39620. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39621. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39622. return false;
  39623. return this._cache._target.equals(this._getTargetPosition())
  39624. && this._cache.alpha === this.alpha
  39625. && this._cache.beta === this.beta
  39626. && this._cache.radius === this.radius
  39627. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39628. };
  39629. // Methods
  39630. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39631. var _this = this;
  39632. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39633. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39634. this._useCtrlForPanning = useCtrlForPanning;
  39635. this._panningMouseButton = panningMouseButton;
  39636. this.inputs.attachElement(element, noPreventDefault);
  39637. this._reset = function () {
  39638. _this.inertialAlphaOffset = 0;
  39639. _this.inertialBetaOffset = 0;
  39640. _this.inertialRadiusOffset = 0;
  39641. _this.inertialPanningX = 0;
  39642. _this.inertialPanningY = 0;
  39643. };
  39644. };
  39645. ArcRotateCamera.prototype.detachControl = function (element) {
  39646. this.inputs.detachElement(element);
  39647. if (this._reset) {
  39648. this._reset();
  39649. }
  39650. };
  39651. ArcRotateCamera.prototype._checkInputs = function () {
  39652. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39653. if (this._collisionTriggered) {
  39654. return;
  39655. }
  39656. this.inputs.checkInputs();
  39657. // Inertia
  39658. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39659. if (this.getScene().useRightHandedSystem) {
  39660. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39661. }
  39662. else {
  39663. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39664. }
  39665. this.beta += this.inertialBetaOffset;
  39666. this.radius -= this.inertialRadiusOffset;
  39667. this.inertialAlphaOffset *= this.inertia;
  39668. this.inertialBetaOffset *= this.inertia;
  39669. this.inertialRadiusOffset *= this.inertia;
  39670. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39671. this.inertialAlphaOffset = 0;
  39672. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39673. this.inertialBetaOffset = 0;
  39674. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39675. this.inertialRadiusOffset = 0;
  39676. }
  39677. // Panning inertia
  39678. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39679. if (!this._localDirection) {
  39680. this._localDirection = BABYLON.Vector3.Zero();
  39681. this._transformedDirection = BABYLON.Vector3.Zero();
  39682. }
  39683. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39684. this._localDirection.multiplyInPlace(this.panningAxis);
  39685. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39686. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39687. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39688. if (!this.panningAxis.y) {
  39689. this._transformedDirection.y = 0;
  39690. }
  39691. if (!this._targetHost) {
  39692. if (this.panningDistanceLimit) {
  39693. this._transformedDirection.addInPlace(this._target);
  39694. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39695. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39696. this._target.copyFrom(this._transformedDirection);
  39697. }
  39698. }
  39699. else {
  39700. this._target.addInPlace(this._transformedDirection);
  39701. }
  39702. }
  39703. this.inertialPanningX *= this.panningInertia;
  39704. this.inertialPanningY *= this.panningInertia;
  39705. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39706. this.inertialPanningX = 0;
  39707. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39708. this.inertialPanningY = 0;
  39709. }
  39710. // Limits
  39711. this._checkLimits();
  39712. _super.prototype._checkInputs.call(this);
  39713. };
  39714. ArcRotateCamera.prototype._checkLimits = function () {
  39715. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39716. if (this.allowUpsideDown && this.beta > Math.PI) {
  39717. this.beta = this.beta - (2 * Math.PI);
  39718. }
  39719. }
  39720. else {
  39721. if (this.beta < this.lowerBetaLimit) {
  39722. this.beta = this.lowerBetaLimit;
  39723. }
  39724. }
  39725. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39726. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39727. this.beta = this.beta + (2 * Math.PI);
  39728. }
  39729. }
  39730. else {
  39731. if (this.beta > this.upperBetaLimit) {
  39732. this.beta = this.upperBetaLimit;
  39733. }
  39734. }
  39735. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39736. this.alpha = this.lowerAlphaLimit;
  39737. }
  39738. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39739. this.alpha = this.upperAlphaLimit;
  39740. }
  39741. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39742. this.radius = this.lowerRadiusLimit;
  39743. }
  39744. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39745. this.radius = this.upperRadiusLimit;
  39746. }
  39747. };
  39748. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39749. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39750. this.radius = radiusv3.length();
  39751. if (this.radius === 0) {
  39752. this.radius = 0.0001; // Just to avoid division by zero
  39753. }
  39754. // Alpha
  39755. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39756. if (radiusv3.z < 0) {
  39757. this.alpha = 2 * Math.PI - this.alpha;
  39758. }
  39759. // Beta
  39760. this.beta = Math.acos(radiusv3.y / this.radius);
  39761. this._checkLimits();
  39762. };
  39763. ArcRotateCamera.prototype.setPosition = function (position) {
  39764. if (this.position.equals(position)) {
  39765. return;
  39766. }
  39767. this.position.copyFrom(position);
  39768. this.rebuildAnglesAndRadius();
  39769. };
  39770. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39771. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39772. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39773. if (target.getBoundingInfo) {
  39774. if (toBoundingCenter) {
  39775. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39776. }
  39777. else {
  39778. this._targetBoundingCenter = null;
  39779. }
  39780. this._targetHost = target;
  39781. this._target = this._getTargetPosition();
  39782. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39783. }
  39784. else {
  39785. var newTarget = target;
  39786. var currentTarget = this._getTargetPosition();
  39787. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39788. return;
  39789. }
  39790. this._targetHost = null;
  39791. this._target = newTarget;
  39792. this._targetBoundingCenter = null;
  39793. this.onMeshTargetChangedObservable.notifyObservers(null);
  39794. }
  39795. this.rebuildAnglesAndRadius();
  39796. };
  39797. ArcRotateCamera.prototype._getViewMatrix = function () {
  39798. // Compute
  39799. var cosa = Math.cos(this.alpha);
  39800. var sina = Math.sin(this.alpha);
  39801. var cosb = Math.cos(this.beta);
  39802. var sinb = Math.sin(this.beta);
  39803. if (sinb === 0) {
  39804. sinb = 0.0001;
  39805. }
  39806. var target = this._getTargetPosition();
  39807. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39808. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39809. if (!this._collider) {
  39810. this._collider = new BABYLON.Collider();
  39811. }
  39812. this._collider.radius = this.collisionRadius;
  39813. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39814. this._collisionTriggered = true;
  39815. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39816. }
  39817. else {
  39818. this.position.copyFrom(this._newPosition);
  39819. var up = this.upVector;
  39820. if (this.allowUpsideDown && sinb < 0) {
  39821. up = up.clone();
  39822. up = up.negate();
  39823. }
  39824. if (this.getScene().useRightHandedSystem) {
  39825. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39826. }
  39827. else {
  39828. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39829. }
  39830. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39831. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39832. }
  39833. this._currentTarget = target;
  39834. return this._viewMatrix;
  39835. };
  39836. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39837. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39838. meshes = meshes || this.getScene().meshes;
  39839. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39840. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39841. this.radius = distance * this.zoomOnFactor;
  39842. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39843. };
  39844. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39845. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39846. var meshesOrMinMaxVector;
  39847. var distance;
  39848. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39849. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39850. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39851. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39852. }
  39853. else {
  39854. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39855. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39856. distance = minMaxVectorAndDistance.distance;
  39857. }
  39858. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39859. if (!doNotUpdateMaxZ) {
  39860. this.maxZ = distance * 2;
  39861. }
  39862. };
  39863. /**
  39864. * @override
  39865. * Override Camera.createRigCamera
  39866. */
  39867. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39868. var alphaShift = 0;
  39869. switch (this.cameraRigMode) {
  39870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39873. case BABYLON.Camera.RIG_MODE_VR:
  39874. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39875. break;
  39876. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39877. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39878. break;
  39879. }
  39880. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39881. rigCam._cameraRigParams = {};
  39882. return rigCam;
  39883. };
  39884. /**
  39885. * @override
  39886. * Override Camera._updateRigCameras
  39887. */
  39888. ArcRotateCamera.prototype._updateRigCameras = function () {
  39889. var camLeft = this._rigCameras[0];
  39890. var camRight = this._rigCameras[1];
  39891. camLeft.beta = camRight.beta = this.beta;
  39892. camLeft.radius = camRight.radius = this.radius;
  39893. switch (this.cameraRigMode) {
  39894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39897. case BABYLON.Camera.RIG_MODE_VR:
  39898. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39899. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39900. break;
  39901. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39902. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39903. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39904. break;
  39905. }
  39906. _super.prototype._updateRigCameras.call(this);
  39907. };
  39908. ArcRotateCamera.prototype.dispose = function () {
  39909. this.inputs.clear();
  39910. _super.prototype.dispose.call(this);
  39911. };
  39912. ArcRotateCamera.prototype.getClassName = function () {
  39913. return "ArcRotateCamera";
  39914. };
  39915. __decorate([
  39916. BABYLON.serialize()
  39917. ], ArcRotateCamera.prototype, "alpha", void 0);
  39918. __decorate([
  39919. BABYLON.serialize()
  39920. ], ArcRotateCamera.prototype, "beta", void 0);
  39921. __decorate([
  39922. BABYLON.serialize()
  39923. ], ArcRotateCamera.prototype, "radius", void 0);
  39924. __decorate([
  39925. BABYLON.serializeAsVector3("target")
  39926. ], ArcRotateCamera.prototype, "_target", void 0);
  39927. __decorate([
  39928. BABYLON.serialize()
  39929. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39930. __decorate([
  39931. BABYLON.serialize()
  39932. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39933. __decorate([
  39934. BABYLON.serialize()
  39935. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39936. __decorate([
  39937. BABYLON.serialize()
  39938. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39939. __decorate([
  39940. BABYLON.serialize()
  39941. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39942. __decorate([
  39943. BABYLON.serialize()
  39944. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39945. __decorate([
  39946. BABYLON.serialize()
  39947. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39948. __decorate([
  39949. BABYLON.serialize()
  39950. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39951. __decorate([
  39952. BABYLON.serialize()
  39953. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39954. __decorate([
  39955. BABYLON.serialize()
  39956. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39957. __decorate([
  39958. BABYLON.serialize()
  39959. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39960. __decorate([
  39961. BABYLON.serialize()
  39962. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39963. __decorate([
  39964. BABYLON.serialize()
  39965. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39966. __decorate([
  39967. BABYLON.serializeAsVector3()
  39968. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39969. __decorate([
  39970. BABYLON.serialize()
  39971. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39972. __decorate([
  39973. BABYLON.serialize()
  39974. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39975. __decorate([
  39976. BABYLON.serialize()
  39977. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39978. return ArcRotateCamera;
  39979. }(BABYLON.TargetCamera));
  39980. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39981. })(BABYLON || (BABYLON = {}));
  39982. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39983. var BABYLON;
  39984. (function (BABYLON) {
  39985. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39986. __extends(ArcRotateCameraInputsManager, _super);
  39987. function ArcRotateCameraInputsManager(camera) {
  39988. return _super.call(this, camera) || this;
  39989. }
  39990. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39991. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39992. return this;
  39993. };
  39994. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39995. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39996. return this;
  39997. };
  39998. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39999. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40000. return this;
  40001. };
  40002. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40003. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40004. return this;
  40005. };
  40006. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40007. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40008. return this;
  40009. };
  40010. return ArcRotateCameraInputsManager;
  40011. }(BABYLON.CameraInputsManager));
  40012. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40013. })(BABYLON || (BABYLON = {}));
  40014. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40015. var BABYLON;
  40016. (function (BABYLON) {
  40017. var HemisphericLight = /** @class */ (function (_super) {
  40018. __extends(HemisphericLight, _super);
  40019. /**
  40020. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40021. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40022. * The HemisphericLight can't cast shadows.
  40023. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40024. */
  40025. function HemisphericLight(name, direction, scene) {
  40026. var _this = _super.call(this, name, scene) || this;
  40027. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40028. _this.direction = direction || BABYLON.Vector3.Up();
  40029. return _this;
  40030. }
  40031. HemisphericLight.prototype._buildUniformLayout = function () {
  40032. this._uniformBuffer.addUniform("vLightData", 4);
  40033. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40034. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40035. this._uniformBuffer.addUniform("vLightGround", 3);
  40036. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40037. this._uniformBuffer.addUniform("depthValues", 2);
  40038. this._uniformBuffer.create();
  40039. };
  40040. /**
  40041. * Returns the string "HemisphericLight".
  40042. */
  40043. HemisphericLight.prototype.getClassName = function () {
  40044. return "HemisphericLight";
  40045. };
  40046. /**
  40047. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40048. * Returns the updated direction.
  40049. */
  40050. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40051. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40052. return this.direction;
  40053. };
  40054. HemisphericLight.prototype.getShadowGenerator = function () {
  40055. return null;
  40056. };
  40057. /**
  40058. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40059. * Returns the HemisphericLight.
  40060. */
  40061. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40062. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40063. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40064. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40065. return this;
  40066. };
  40067. HemisphericLight.prototype._getWorldMatrix = function () {
  40068. if (!this._worldMatrix) {
  40069. this._worldMatrix = BABYLON.Matrix.Identity();
  40070. }
  40071. return this._worldMatrix;
  40072. };
  40073. /**
  40074. * Returns the integer 3.
  40075. */
  40076. HemisphericLight.prototype.getTypeID = function () {
  40077. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40078. };
  40079. __decorate([
  40080. BABYLON.serializeAsColor3()
  40081. ], HemisphericLight.prototype, "groundColor", void 0);
  40082. __decorate([
  40083. BABYLON.serializeAsVector3()
  40084. ], HemisphericLight.prototype, "direction", void 0);
  40085. return HemisphericLight;
  40086. }(BABYLON.Light));
  40087. BABYLON.HemisphericLight = HemisphericLight;
  40088. })(BABYLON || (BABYLON = {}));
  40089. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40090. var BABYLON;
  40091. (function (BABYLON) {
  40092. var ShadowLight = /** @class */ (function (_super) {
  40093. __extends(ShadowLight, _super);
  40094. function ShadowLight() {
  40095. var _this = _super !== null && _super.apply(this, arguments) || this;
  40096. _this._needProjectionMatrixCompute = true;
  40097. return _this;
  40098. }
  40099. Object.defineProperty(ShadowLight.prototype, "direction", {
  40100. get: function () {
  40101. return this._direction;
  40102. },
  40103. set: function (value) {
  40104. this._direction = value;
  40105. },
  40106. enumerable: true,
  40107. configurable: true
  40108. });
  40109. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40110. get: function () {
  40111. return this._shadowMinZ;
  40112. },
  40113. set: function (value) {
  40114. this._shadowMinZ = value;
  40115. this.forceProjectionMatrixCompute();
  40116. },
  40117. enumerable: true,
  40118. configurable: true
  40119. });
  40120. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40121. get: function () {
  40122. return this._shadowMaxZ;
  40123. },
  40124. set: function (value) {
  40125. this._shadowMaxZ = value;
  40126. this.forceProjectionMatrixCompute();
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. /**
  40132. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40133. */
  40134. ShadowLight.prototype.computeTransformedInformation = function () {
  40135. if (this.parent && this.parent.getWorldMatrix) {
  40136. if (!this.transformedPosition) {
  40137. this.transformedPosition = BABYLON.Vector3.Zero();
  40138. }
  40139. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40140. // In case the direction is present.
  40141. if (this.direction) {
  40142. if (!this.transformedDirection) {
  40143. this.transformedDirection = BABYLON.Vector3.Zero();
  40144. }
  40145. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40146. }
  40147. return true;
  40148. }
  40149. return false;
  40150. };
  40151. /**
  40152. * Return the depth scale used for the shadow map.
  40153. */
  40154. ShadowLight.prototype.getDepthScale = function () {
  40155. return 50.0;
  40156. };
  40157. /**
  40158. * Returns the light direction (Vector3) for any passed face index.
  40159. */
  40160. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40161. return this.transformedDirection ? this.transformedDirection : this.direction;
  40162. };
  40163. /**
  40164. * Returns the DirectionalLight absolute position in the World.
  40165. */
  40166. ShadowLight.prototype.getAbsolutePosition = function () {
  40167. return this.transformedPosition ? this.transformedPosition : this.position;
  40168. };
  40169. /**
  40170. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40171. * Returns the updated DirectionalLight direction (Vector3).
  40172. */
  40173. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40174. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40175. return this.direction;
  40176. };
  40177. /**
  40178. * Returns the light rotation (Vector3).
  40179. */
  40180. ShadowLight.prototype.getRotation = function () {
  40181. this.direction.normalize();
  40182. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40183. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40184. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40185. };
  40186. /**
  40187. * Boolean : false by default.
  40188. */
  40189. ShadowLight.prototype.needCube = function () {
  40190. return false;
  40191. };
  40192. /**
  40193. * Specifies wether or not the projection matrix should be recomputed this frame.
  40194. */
  40195. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40196. return this._needProjectionMatrixCompute;
  40197. };
  40198. /**
  40199. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40200. */
  40201. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40202. this._needProjectionMatrixCompute = true;
  40203. };
  40204. /**
  40205. * Get the world matrix of the sahdow lights.
  40206. */
  40207. ShadowLight.prototype._getWorldMatrix = function () {
  40208. if (!this._worldMatrix) {
  40209. this._worldMatrix = BABYLON.Matrix.Identity();
  40210. }
  40211. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40212. return this._worldMatrix;
  40213. };
  40214. /**
  40215. * Gets the minZ used for shadow according to both the scene and the light.
  40216. * @param activeCamera
  40217. */
  40218. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40219. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40220. };
  40221. /**
  40222. * Gets the maxZ used for shadow according to both the scene and the light.
  40223. * @param activeCamera
  40224. */
  40225. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40226. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40227. };
  40228. /**
  40229. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40230. * Returns the light.
  40231. */
  40232. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40233. if (this.customProjectionMatrixBuilder) {
  40234. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40235. }
  40236. else {
  40237. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40238. }
  40239. return this;
  40240. };
  40241. __decorate([
  40242. BABYLON.serializeAsVector3()
  40243. ], ShadowLight.prototype, "position", void 0);
  40244. __decorate([
  40245. BABYLON.serializeAsVector3()
  40246. ], ShadowLight.prototype, "direction", null);
  40247. __decorate([
  40248. BABYLON.serialize()
  40249. ], ShadowLight.prototype, "shadowMinZ", null);
  40250. __decorate([
  40251. BABYLON.serialize()
  40252. ], ShadowLight.prototype, "shadowMaxZ", null);
  40253. return ShadowLight;
  40254. }(BABYLON.Light));
  40255. BABYLON.ShadowLight = ShadowLight;
  40256. })(BABYLON || (BABYLON = {}));
  40257. //# sourceMappingURL=babylon.shadowLight.js.map
  40258. var BABYLON;
  40259. (function (BABYLON) {
  40260. var PointLight = /** @class */ (function (_super) {
  40261. __extends(PointLight, _super);
  40262. /**
  40263. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40264. * A PointLight emits the light in every direction.
  40265. * It can cast shadows.
  40266. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40267. * ```javascript
  40268. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40269. * ```
  40270. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40271. */
  40272. function PointLight(name, position, scene) {
  40273. var _this = _super.call(this, name, scene) || this;
  40274. _this._shadowAngle = Math.PI / 2;
  40275. _this.position = position;
  40276. return _this;
  40277. }
  40278. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40279. /**
  40280. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40281. * This specifies what angle the shadow will use to be created.
  40282. *
  40283. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40284. */
  40285. get: function () {
  40286. return this._shadowAngle;
  40287. },
  40288. /**
  40289. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40290. * This specifies what angle the shadow will use to be created.
  40291. *
  40292. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40293. */
  40294. set: function (value) {
  40295. this._shadowAngle = value;
  40296. this.forceProjectionMatrixCompute();
  40297. },
  40298. enumerable: true,
  40299. configurable: true
  40300. });
  40301. Object.defineProperty(PointLight.prototype, "direction", {
  40302. get: function () {
  40303. return this._direction;
  40304. },
  40305. /**
  40306. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40307. */
  40308. set: function (value) {
  40309. var previousNeedCube = this.needCube();
  40310. this._direction = value;
  40311. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40312. this._shadowGenerator.recreateShadowMap();
  40313. }
  40314. },
  40315. enumerable: true,
  40316. configurable: true
  40317. });
  40318. /**
  40319. * Returns the string "PointLight"
  40320. */
  40321. PointLight.prototype.getClassName = function () {
  40322. return "PointLight";
  40323. };
  40324. /**
  40325. * Returns the integer 0.
  40326. */
  40327. PointLight.prototype.getTypeID = function () {
  40328. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40329. };
  40330. /**
  40331. * Specifies wether or not the shadowmap should be a cube texture.
  40332. */
  40333. PointLight.prototype.needCube = function () {
  40334. return !this.direction;
  40335. };
  40336. /**
  40337. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40338. */
  40339. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40340. if (this.direction) {
  40341. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40342. }
  40343. else {
  40344. switch (faceIndex) {
  40345. case 0:
  40346. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40347. case 1:
  40348. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40349. case 2:
  40350. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40351. case 3:
  40352. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40353. case 4:
  40354. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40355. case 5:
  40356. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40357. }
  40358. }
  40359. return BABYLON.Vector3.Zero();
  40360. };
  40361. /**
  40362. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40363. * - fov = PI / 2
  40364. * - aspect ratio : 1.0
  40365. * - z-near and far equal to the active camera minZ and maxZ.
  40366. * Returns the PointLight.
  40367. */
  40368. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40369. var activeCamera = this.getScene().activeCamera;
  40370. if (!activeCamera) {
  40371. return;
  40372. }
  40373. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40374. };
  40375. PointLight.prototype._buildUniformLayout = function () {
  40376. this._uniformBuffer.addUniform("vLightData", 4);
  40377. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40378. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40379. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40380. this._uniformBuffer.addUniform("depthValues", 2);
  40381. this._uniformBuffer.create();
  40382. };
  40383. /**
  40384. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40385. * Returns the PointLight.
  40386. */
  40387. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40388. if (this.computeTransformedInformation()) {
  40389. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40390. return this;
  40391. }
  40392. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40393. return this;
  40394. };
  40395. __decorate([
  40396. BABYLON.serialize()
  40397. ], PointLight.prototype, "shadowAngle", null);
  40398. return PointLight;
  40399. }(BABYLON.ShadowLight));
  40400. BABYLON.PointLight = PointLight;
  40401. })(BABYLON || (BABYLON = {}));
  40402. //# sourceMappingURL=babylon.pointLight.js.map
  40403. var BABYLON;
  40404. (function (BABYLON) {
  40405. var DirectionalLight = /** @class */ (function (_super) {
  40406. __extends(DirectionalLight, _super);
  40407. /**
  40408. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40409. * The directional light is emitted from everywhere in the given direction.
  40410. * It can cast shawdows.
  40411. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40412. */
  40413. function DirectionalLight(name, direction, scene) {
  40414. var _this = _super.call(this, name, scene) || this;
  40415. _this._shadowFrustumSize = 0;
  40416. _this._shadowOrthoScale = 0.5;
  40417. _this.autoUpdateExtends = true;
  40418. // Cache
  40419. _this._orthoLeft = Number.MAX_VALUE;
  40420. _this._orthoRight = Number.MIN_VALUE;
  40421. _this._orthoTop = Number.MIN_VALUE;
  40422. _this._orthoBottom = Number.MAX_VALUE;
  40423. _this.position = direction.scale(-1.0);
  40424. _this.direction = direction;
  40425. return _this;
  40426. }
  40427. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40428. /**
  40429. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40430. */
  40431. get: function () {
  40432. return this._shadowFrustumSize;
  40433. },
  40434. /**
  40435. * Specifies a fix frustum size for the shadow generation.
  40436. */
  40437. set: function (value) {
  40438. this._shadowFrustumSize = value;
  40439. this.forceProjectionMatrixCompute();
  40440. },
  40441. enumerable: true,
  40442. configurable: true
  40443. });
  40444. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40445. get: function () {
  40446. return this._shadowOrthoScale;
  40447. },
  40448. set: function (value) {
  40449. this._shadowOrthoScale = value;
  40450. this.forceProjectionMatrixCompute();
  40451. },
  40452. enumerable: true,
  40453. configurable: true
  40454. });
  40455. /**
  40456. * Returns the string "DirectionalLight".
  40457. */
  40458. DirectionalLight.prototype.getClassName = function () {
  40459. return "DirectionalLight";
  40460. };
  40461. /**
  40462. * Returns the integer 1.
  40463. */
  40464. DirectionalLight.prototype.getTypeID = function () {
  40465. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40466. };
  40467. /**
  40468. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40469. * Returns the DirectionalLight Shadow projection matrix.
  40470. */
  40471. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40472. if (this.shadowFrustumSize > 0) {
  40473. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40474. }
  40475. else {
  40476. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40477. }
  40478. };
  40479. /**
  40480. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40481. * Returns the DirectionalLight Shadow projection matrix.
  40482. */
  40483. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40484. var activeCamera = this.getScene().activeCamera;
  40485. if (!activeCamera) {
  40486. return;
  40487. }
  40488. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40489. };
  40490. /**
  40491. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40492. * Returns the DirectionalLight Shadow projection matrix.
  40493. */
  40494. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40495. var activeCamera = this.getScene().activeCamera;
  40496. if (!activeCamera) {
  40497. return;
  40498. }
  40499. // Check extends
  40500. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40501. var tempVector3 = BABYLON.Vector3.Zero();
  40502. this._orthoLeft = Number.MAX_VALUE;
  40503. this._orthoRight = Number.MIN_VALUE;
  40504. this._orthoTop = Number.MIN_VALUE;
  40505. this._orthoBottom = Number.MAX_VALUE;
  40506. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40507. var mesh = renderList[meshIndex];
  40508. if (!mesh) {
  40509. continue;
  40510. }
  40511. var boundingInfo = mesh.getBoundingInfo();
  40512. var boundingBox = boundingInfo.boundingBox;
  40513. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40514. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40515. if (tempVector3.x < this._orthoLeft)
  40516. this._orthoLeft = tempVector3.x;
  40517. if (tempVector3.y < this._orthoBottom)
  40518. this._orthoBottom = tempVector3.y;
  40519. if (tempVector3.x > this._orthoRight)
  40520. this._orthoRight = tempVector3.x;
  40521. if (tempVector3.y > this._orthoTop)
  40522. this._orthoTop = tempVector3.y;
  40523. }
  40524. }
  40525. }
  40526. var xOffset = this._orthoRight - this._orthoLeft;
  40527. var yOffset = this._orthoTop - this._orthoBottom;
  40528. 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);
  40529. };
  40530. DirectionalLight.prototype._buildUniformLayout = function () {
  40531. this._uniformBuffer.addUniform("vLightData", 4);
  40532. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40533. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40534. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40535. this._uniformBuffer.addUniform("depthValues", 2);
  40536. this._uniformBuffer.create();
  40537. };
  40538. /**
  40539. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40540. * Returns the DirectionalLight.
  40541. */
  40542. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40543. if (this.computeTransformedInformation()) {
  40544. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40545. return this;
  40546. }
  40547. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40548. return this;
  40549. };
  40550. /**
  40551. * Gets the minZ used for shadow according to both the scene and the light.
  40552. *
  40553. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40554. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40555. * @param activeCamera
  40556. */
  40557. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40558. return 1;
  40559. };
  40560. /**
  40561. * Gets the maxZ used for shadow according to both the scene and the light.
  40562. *
  40563. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40564. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40565. * @param activeCamera
  40566. */
  40567. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40568. return 1;
  40569. };
  40570. __decorate([
  40571. BABYLON.serialize()
  40572. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40573. __decorate([
  40574. BABYLON.serialize()
  40575. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40576. __decorate([
  40577. BABYLON.serialize()
  40578. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40579. return DirectionalLight;
  40580. }(BABYLON.ShadowLight));
  40581. BABYLON.DirectionalLight = DirectionalLight;
  40582. })(BABYLON || (BABYLON = {}));
  40583. //# sourceMappingURL=babylon.directionalLight.js.map
  40584. var BABYLON;
  40585. (function (BABYLON) {
  40586. var SpotLight = /** @class */ (function (_super) {
  40587. __extends(SpotLight, _super);
  40588. /**
  40589. * Creates a SpotLight object in the scene with the passed parameters :
  40590. * - `position` (Vector3) is the initial SpotLight position,
  40591. * - `direction` (Vector3) is the initial SpotLight direction,
  40592. * - `angle` (float, in radians) is the spot light cone angle,
  40593. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40594. * A spot light is a simply light oriented cone.
  40595. * It can cast shadows.
  40596. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40597. */
  40598. function SpotLight(name, position, direction, angle, exponent, scene) {
  40599. var _this = _super.call(this, name, scene) || this;
  40600. _this.position = position;
  40601. _this.direction = direction;
  40602. _this.angle = angle;
  40603. _this.exponent = exponent;
  40604. return _this;
  40605. }
  40606. Object.defineProperty(SpotLight.prototype, "angle", {
  40607. get: function () {
  40608. return this._angle;
  40609. },
  40610. set: function (value) {
  40611. this._angle = value;
  40612. this.forceProjectionMatrixCompute();
  40613. },
  40614. enumerable: true,
  40615. configurable: true
  40616. });
  40617. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40618. get: function () {
  40619. return this._shadowAngleScale;
  40620. },
  40621. /**
  40622. * Allows scaling the angle of the light for shadow generation only.
  40623. */
  40624. set: function (value) {
  40625. this._shadowAngleScale = value;
  40626. this.forceProjectionMatrixCompute();
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. /**
  40632. * Returns the string "SpotLight".
  40633. */
  40634. SpotLight.prototype.getClassName = function () {
  40635. return "SpotLight";
  40636. };
  40637. /**
  40638. * Returns the integer 2.
  40639. */
  40640. SpotLight.prototype.getTypeID = function () {
  40641. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40642. };
  40643. /**
  40644. * 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.
  40645. * Returns the SpotLight.
  40646. */
  40647. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40648. var activeCamera = this.getScene().activeCamera;
  40649. if (!activeCamera) {
  40650. return;
  40651. }
  40652. this._shadowAngleScale = this._shadowAngleScale || 1;
  40653. var angle = this._shadowAngleScale * this._angle;
  40654. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40655. };
  40656. SpotLight.prototype._buildUniformLayout = function () {
  40657. this._uniformBuffer.addUniform("vLightData", 4);
  40658. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40659. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40660. this._uniformBuffer.addUniform("vLightDirection", 3);
  40661. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40662. this._uniformBuffer.addUniform("depthValues", 2);
  40663. this._uniformBuffer.create();
  40664. };
  40665. /**
  40666. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40667. * Return the SpotLight.
  40668. */
  40669. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40670. var normalizeDirection;
  40671. if (this.computeTransformedInformation()) {
  40672. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40673. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40674. }
  40675. else {
  40676. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40677. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40678. }
  40679. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40680. return this;
  40681. };
  40682. __decorate([
  40683. BABYLON.serialize()
  40684. ], SpotLight.prototype, "angle", null);
  40685. __decorate([
  40686. BABYLON.serialize()
  40687. /**
  40688. * Allows scaling the angle of the light for shadow generation only.
  40689. */
  40690. ], SpotLight.prototype, "shadowAngleScale", null);
  40691. __decorate([
  40692. BABYLON.serialize()
  40693. ], SpotLight.prototype, "exponent", void 0);
  40694. return SpotLight;
  40695. }(BABYLON.ShadowLight));
  40696. BABYLON.SpotLight = SpotLight;
  40697. })(BABYLON || (BABYLON = {}));
  40698. //# sourceMappingURL=babylon.spotLight.js.map
  40699. var BABYLON;
  40700. (function (BABYLON) {
  40701. var AnimationRange = /** @class */ (function () {
  40702. function AnimationRange(name, from, to) {
  40703. this.name = name;
  40704. this.from = from;
  40705. this.to = to;
  40706. }
  40707. AnimationRange.prototype.clone = function () {
  40708. return new AnimationRange(this.name, this.from, this.to);
  40709. };
  40710. return AnimationRange;
  40711. }());
  40712. BABYLON.AnimationRange = AnimationRange;
  40713. /**
  40714. * Composed of a frame, and an action function
  40715. */
  40716. var AnimationEvent = /** @class */ (function () {
  40717. function AnimationEvent(frame, action, onlyOnce) {
  40718. this.frame = frame;
  40719. this.action = action;
  40720. this.onlyOnce = onlyOnce;
  40721. this.isDone = false;
  40722. }
  40723. return AnimationEvent;
  40724. }());
  40725. BABYLON.AnimationEvent = AnimationEvent;
  40726. var PathCursor = /** @class */ (function () {
  40727. function PathCursor(path) {
  40728. this.path = path;
  40729. this._onchange = new Array();
  40730. this.value = 0;
  40731. this.animations = new Array();
  40732. }
  40733. PathCursor.prototype.getPoint = function () {
  40734. var point = this.path.getPointAtLengthPosition(this.value);
  40735. return new BABYLON.Vector3(point.x, 0, point.y);
  40736. };
  40737. PathCursor.prototype.moveAhead = function (step) {
  40738. if (step === void 0) { step = 0.002; }
  40739. this.move(step);
  40740. return this;
  40741. };
  40742. PathCursor.prototype.moveBack = function (step) {
  40743. if (step === void 0) { step = 0.002; }
  40744. this.move(-step);
  40745. return this;
  40746. };
  40747. PathCursor.prototype.move = function (step) {
  40748. if (Math.abs(step) > 1) {
  40749. throw "step size should be less than 1.";
  40750. }
  40751. this.value += step;
  40752. this.ensureLimits();
  40753. this.raiseOnChange();
  40754. return this;
  40755. };
  40756. PathCursor.prototype.ensureLimits = function () {
  40757. while (this.value > 1) {
  40758. this.value -= 1;
  40759. }
  40760. while (this.value < 0) {
  40761. this.value += 1;
  40762. }
  40763. return this;
  40764. };
  40765. // used by animation engine
  40766. PathCursor.prototype.raiseOnChange = function () {
  40767. var _this = this;
  40768. this._onchange.forEach(function (f) { return f(_this); });
  40769. return this;
  40770. };
  40771. PathCursor.prototype.onchange = function (f) {
  40772. this._onchange.push(f);
  40773. return this;
  40774. };
  40775. return PathCursor;
  40776. }());
  40777. BABYLON.PathCursor = PathCursor;
  40778. var Animation = /** @class */ (function () {
  40779. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40780. this.name = name;
  40781. this.targetProperty = targetProperty;
  40782. this.framePerSecond = framePerSecond;
  40783. this.dataType = dataType;
  40784. this.loopMode = loopMode;
  40785. this.enableBlending = enableBlending;
  40786. this._runtimeAnimations = new Array();
  40787. // The set of event that will be linked to this animation
  40788. this._events = new Array();
  40789. this.blendingSpeed = 0.01;
  40790. this._ranges = {};
  40791. this.targetPropertyPath = targetProperty.split(".");
  40792. this.dataType = dataType;
  40793. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40794. }
  40795. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40796. var dataType = undefined;
  40797. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40798. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40799. }
  40800. else if (from instanceof BABYLON.Quaternion) {
  40801. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40802. }
  40803. else if (from instanceof BABYLON.Vector3) {
  40804. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40805. }
  40806. else if (from instanceof BABYLON.Vector2) {
  40807. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40808. }
  40809. else if (from instanceof BABYLON.Color3) {
  40810. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40811. }
  40812. else if (from instanceof BABYLON.Size) {
  40813. dataType = Animation.ANIMATIONTYPE_SIZE;
  40814. }
  40815. if (dataType == undefined) {
  40816. return null;
  40817. }
  40818. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40819. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40820. animation.setKeys(keys);
  40821. if (easingFunction !== undefined) {
  40822. animation.setEasingFunction(easingFunction);
  40823. }
  40824. return animation;
  40825. };
  40826. /**
  40827. * Sets up an animation.
  40828. * @param property the property to animate
  40829. * @param animationType the animation type to apply
  40830. * @param easingFunction the easing function used in the animation
  40831. * @returns The created animation
  40832. */
  40833. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40834. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40835. animation.setEasingFunction(easingFunction);
  40836. return animation;
  40837. };
  40838. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40839. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40840. if (!animation) {
  40841. return null;
  40842. }
  40843. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40844. };
  40845. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40846. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40847. if (!animation) {
  40848. return null;
  40849. }
  40850. node.animations.push(animation);
  40851. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40852. };
  40853. /**
  40854. * Transition property of the Camera to the target Value.
  40855. * @param property The property to transition
  40856. * @param targetValue The target Value of the property
  40857. * @param host The object where the property to animate belongs
  40858. * @param scene Scene used to run the animation
  40859. * @param frameRate Framerate (in frame/s) to use
  40860. * @param transition The transition type we want to use
  40861. * @param duration The duration of the animation, in milliseconds
  40862. * @param onAnimationEnd Call back trigger at the end of the animation.
  40863. */
  40864. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40865. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40866. if (duration <= 0) {
  40867. host[property] = targetValue;
  40868. if (onAnimationEnd) {
  40869. onAnimationEnd();
  40870. }
  40871. return null;
  40872. }
  40873. var endFrame = frameRate * (duration / 1000);
  40874. transition.setKeys([{
  40875. frame: 0,
  40876. value: host[property].clone ? host[property].clone() : host[property]
  40877. },
  40878. {
  40879. frame: endFrame,
  40880. value: targetValue
  40881. }]);
  40882. if (!host.animations) {
  40883. host.animations = [];
  40884. }
  40885. host.animations.push(transition);
  40886. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40887. animation.onAnimationEnd = onAnimationEnd;
  40888. return animation;
  40889. };
  40890. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40891. /**
  40892. * Return the array of runtime animations currently using this animation
  40893. */
  40894. get: function () {
  40895. return this._runtimeAnimations;
  40896. },
  40897. enumerable: true,
  40898. configurable: true
  40899. });
  40900. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40901. get: function () {
  40902. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40903. var runtimeAnimation = _a[_i];
  40904. if (!runtimeAnimation.isStopped) {
  40905. return true;
  40906. }
  40907. }
  40908. return false;
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. // Methods
  40914. /**
  40915. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40916. */
  40917. Animation.prototype.toString = function (fullDetails) {
  40918. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40919. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40920. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40921. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40922. if (fullDetails) {
  40923. ret += ", Ranges: {";
  40924. var first = true;
  40925. for (var name in this._ranges) {
  40926. if (first) {
  40927. ret += ", ";
  40928. first = false;
  40929. }
  40930. ret += name;
  40931. }
  40932. ret += "}";
  40933. }
  40934. return ret;
  40935. };
  40936. /**
  40937. * Add an event to this animation.
  40938. */
  40939. Animation.prototype.addEvent = function (event) {
  40940. this._events.push(event);
  40941. };
  40942. /**
  40943. * Remove all events found at the given frame
  40944. * @param frame
  40945. */
  40946. Animation.prototype.removeEvents = function (frame) {
  40947. for (var index = 0; index < this._events.length; index++) {
  40948. if (this._events[index].frame === frame) {
  40949. this._events.splice(index, 1);
  40950. index--;
  40951. }
  40952. }
  40953. };
  40954. Animation.prototype.getEvents = function () {
  40955. return this._events;
  40956. };
  40957. Animation.prototype.createRange = function (name, from, to) {
  40958. // check name not already in use; could happen for bones after serialized
  40959. if (!this._ranges[name]) {
  40960. this._ranges[name] = new AnimationRange(name, from, to);
  40961. }
  40962. };
  40963. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40964. if (deleteFrames === void 0) { deleteFrames = true; }
  40965. var range = this._ranges[name];
  40966. if (!range) {
  40967. return;
  40968. }
  40969. if (deleteFrames) {
  40970. var from = range.from;
  40971. var to = range.to;
  40972. // this loop MUST go high to low for multiple splices to work
  40973. for (var key = this._keys.length - 1; key >= 0; key--) {
  40974. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40975. this._keys.splice(key, 1);
  40976. }
  40977. }
  40978. }
  40979. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40980. };
  40981. Animation.prototype.getRange = function (name) {
  40982. return this._ranges[name];
  40983. };
  40984. Animation.prototype.getKeys = function () {
  40985. return this._keys;
  40986. };
  40987. Animation.prototype.getHighestFrame = function () {
  40988. var ret = 0;
  40989. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40990. if (ret < this._keys[key].frame) {
  40991. ret = this._keys[key].frame;
  40992. }
  40993. }
  40994. return ret;
  40995. };
  40996. Animation.prototype.getEasingFunction = function () {
  40997. return this._easingFunction;
  40998. };
  40999. Animation.prototype.setEasingFunction = function (easingFunction) {
  41000. this._easingFunction = easingFunction;
  41001. };
  41002. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41003. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41004. };
  41005. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41006. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41007. };
  41008. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41009. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41010. };
  41011. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41012. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41013. };
  41014. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41015. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41016. };
  41017. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41018. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41019. };
  41020. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41021. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41022. };
  41023. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41024. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41025. };
  41026. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41027. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41028. };
  41029. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41030. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41031. };
  41032. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41033. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41034. };
  41035. Animation.prototype.clone = function () {
  41036. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41037. clone.enableBlending = this.enableBlending;
  41038. clone.blendingSpeed = this.blendingSpeed;
  41039. if (this._keys) {
  41040. clone.setKeys(this._keys);
  41041. }
  41042. if (this._ranges) {
  41043. clone._ranges = {};
  41044. for (var name in this._ranges) {
  41045. var range = this._ranges[name];
  41046. if (!range) {
  41047. continue;
  41048. }
  41049. clone._ranges[name] = range.clone();
  41050. }
  41051. }
  41052. return clone;
  41053. };
  41054. Animation.prototype.setKeys = function (values) {
  41055. this._keys = values.slice(0);
  41056. };
  41057. Animation.prototype.serialize = function () {
  41058. var serializationObject = {};
  41059. serializationObject.name = this.name;
  41060. serializationObject.property = this.targetProperty;
  41061. serializationObject.framePerSecond = this.framePerSecond;
  41062. serializationObject.dataType = this.dataType;
  41063. serializationObject.loopBehavior = this.loopMode;
  41064. serializationObject.enableBlending = this.enableBlending;
  41065. serializationObject.blendingSpeed = this.blendingSpeed;
  41066. var dataType = this.dataType;
  41067. serializationObject.keys = [];
  41068. var keys = this.getKeys();
  41069. for (var index = 0; index < keys.length; index++) {
  41070. var animationKey = keys[index];
  41071. var key = {};
  41072. key.frame = animationKey.frame;
  41073. switch (dataType) {
  41074. case Animation.ANIMATIONTYPE_FLOAT:
  41075. key.values = [animationKey.value];
  41076. break;
  41077. case Animation.ANIMATIONTYPE_QUATERNION:
  41078. case Animation.ANIMATIONTYPE_MATRIX:
  41079. case Animation.ANIMATIONTYPE_VECTOR3:
  41080. case Animation.ANIMATIONTYPE_COLOR3:
  41081. key.values = animationKey.value.asArray();
  41082. break;
  41083. }
  41084. serializationObject.keys.push(key);
  41085. }
  41086. serializationObject.ranges = [];
  41087. for (var name in this._ranges) {
  41088. var source = this._ranges[name];
  41089. if (!source) {
  41090. continue;
  41091. }
  41092. var range = {};
  41093. range.name = name;
  41094. range.from = source.from;
  41095. range.to = source.to;
  41096. serializationObject.ranges.push(range);
  41097. }
  41098. return serializationObject;
  41099. };
  41100. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41101. get: function () {
  41102. return Animation._ANIMATIONTYPE_FLOAT;
  41103. },
  41104. enumerable: true,
  41105. configurable: true
  41106. });
  41107. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41108. get: function () {
  41109. return Animation._ANIMATIONTYPE_VECTOR3;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41115. get: function () {
  41116. return Animation._ANIMATIONTYPE_VECTOR2;
  41117. },
  41118. enumerable: true,
  41119. configurable: true
  41120. });
  41121. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41122. get: function () {
  41123. return Animation._ANIMATIONTYPE_SIZE;
  41124. },
  41125. enumerable: true,
  41126. configurable: true
  41127. });
  41128. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41129. get: function () {
  41130. return Animation._ANIMATIONTYPE_QUATERNION;
  41131. },
  41132. enumerable: true,
  41133. configurable: true
  41134. });
  41135. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41136. get: function () {
  41137. return Animation._ANIMATIONTYPE_MATRIX;
  41138. },
  41139. enumerable: true,
  41140. configurable: true
  41141. });
  41142. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41143. get: function () {
  41144. return Animation._ANIMATIONTYPE_COLOR3;
  41145. },
  41146. enumerable: true,
  41147. configurable: true
  41148. });
  41149. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41150. get: function () {
  41151. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41152. },
  41153. enumerable: true,
  41154. configurable: true
  41155. });
  41156. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41157. get: function () {
  41158. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41159. },
  41160. enumerable: true,
  41161. configurable: true
  41162. });
  41163. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41164. get: function () {
  41165. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41166. },
  41167. enumerable: true,
  41168. configurable: true
  41169. });
  41170. Animation.Parse = function (parsedAnimation) {
  41171. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41172. var dataType = parsedAnimation.dataType;
  41173. var keys = [];
  41174. var data;
  41175. var index;
  41176. if (parsedAnimation.enableBlending) {
  41177. animation.enableBlending = parsedAnimation.enableBlending;
  41178. }
  41179. if (parsedAnimation.blendingSpeed) {
  41180. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41181. }
  41182. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41183. var key = parsedAnimation.keys[index];
  41184. var inTangent;
  41185. var outTangent;
  41186. switch (dataType) {
  41187. case Animation.ANIMATIONTYPE_FLOAT:
  41188. data = key.values[0];
  41189. if (key.values.length >= 1) {
  41190. inTangent = key.values[1];
  41191. }
  41192. if (key.values.length >= 2) {
  41193. outTangent = key.values[2];
  41194. }
  41195. break;
  41196. case Animation.ANIMATIONTYPE_QUATERNION:
  41197. data = BABYLON.Quaternion.FromArray(key.values);
  41198. if (key.values.length >= 8) {
  41199. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41200. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41201. inTangent = _inTangent;
  41202. }
  41203. }
  41204. if (key.values.length >= 12) {
  41205. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41206. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41207. outTangent = _outTangent;
  41208. }
  41209. }
  41210. break;
  41211. case Animation.ANIMATIONTYPE_MATRIX:
  41212. data = BABYLON.Matrix.FromArray(key.values);
  41213. break;
  41214. case Animation.ANIMATIONTYPE_COLOR3:
  41215. data = BABYLON.Color3.FromArray(key.values);
  41216. break;
  41217. case Animation.ANIMATIONTYPE_VECTOR3:
  41218. default:
  41219. data = BABYLON.Vector3.FromArray(key.values);
  41220. break;
  41221. }
  41222. var keyData = {};
  41223. keyData.frame = key.frame;
  41224. keyData.value = data;
  41225. if (inTangent != undefined) {
  41226. keyData.inTangent = inTangent;
  41227. }
  41228. if (outTangent != undefined) {
  41229. keyData.outTangent = outTangent;
  41230. }
  41231. keys.push(keyData);
  41232. }
  41233. animation.setKeys(keys);
  41234. if (parsedAnimation.ranges) {
  41235. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41236. data = parsedAnimation.ranges[index];
  41237. animation.createRange(data.name, data.from, data.to);
  41238. }
  41239. }
  41240. return animation;
  41241. };
  41242. Animation.AppendSerializedAnimations = function (source, destination) {
  41243. if (source.animations) {
  41244. destination.animations = [];
  41245. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41246. var animation = source.animations[animationIndex];
  41247. destination.animations.push(animation.serialize());
  41248. }
  41249. }
  41250. };
  41251. Animation.AllowMatricesInterpolation = false;
  41252. // Statics
  41253. Animation._ANIMATIONTYPE_FLOAT = 0;
  41254. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41255. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41256. Animation._ANIMATIONTYPE_MATRIX = 3;
  41257. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41258. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41259. Animation._ANIMATIONTYPE_SIZE = 6;
  41260. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41261. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41262. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41263. return Animation;
  41264. }());
  41265. BABYLON.Animation = Animation;
  41266. })(BABYLON || (BABYLON = {}));
  41267. //# sourceMappingURL=babylon.animation.js.map
  41268. var BABYLON;
  41269. (function (BABYLON) {
  41270. var RuntimeAnimation = /** @class */ (function () {
  41271. function RuntimeAnimation(target, animation) {
  41272. this._offsetsCache = {};
  41273. this._highLimitsCache = {};
  41274. this._stopped = false;
  41275. this._blendingFactor = 0;
  41276. this._ratioOffset = 0;
  41277. this._animation = animation;
  41278. this._target = target;
  41279. animation._runtimeAnimations.push(this);
  41280. }
  41281. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41282. get: function () {
  41283. return this._animation;
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. RuntimeAnimation.prototype.reset = function () {
  41289. this._offsetsCache = {};
  41290. this._highLimitsCache = {};
  41291. this.currentFrame = 0;
  41292. this._blendingFactor = 0;
  41293. this._originalBlendValue = null;
  41294. };
  41295. RuntimeAnimation.prototype.isStopped = function () {
  41296. return this._stopped;
  41297. };
  41298. RuntimeAnimation.prototype.dispose = function () {
  41299. var index = this._animation.runtimeAnimations.indexOf(this);
  41300. if (index > -1) {
  41301. this._animation.runtimeAnimations.splice(index, 1);
  41302. }
  41303. };
  41304. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41305. if (typeof value === "function") {
  41306. return value();
  41307. }
  41308. return value;
  41309. };
  41310. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41311. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41312. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41313. }
  41314. this.currentFrame = currentFrame;
  41315. var keys = this._animation.getKeys();
  41316. // Try to get a hash to find the right key
  41317. 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));
  41318. if (keys[startKeyIndex].frame >= currentFrame) {
  41319. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41320. startKeyIndex--;
  41321. }
  41322. }
  41323. for (var key = startKeyIndex; key < keys.length; key++) {
  41324. var endKey = keys[key + 1];
  41325. if (endKey.frame >= currentFrame) {
  41326. var startKey = keys[key];
  41327. var startValue = this._getKeyValue(startKey.value);
  41328. var endValue = this._getKeyValue(endKey.value);
  41329. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41330. var frameDelta = endKey.frame - startKey.frame;
  41331. // gradient : percent of currentFrame between the frame inf and the frame sup
  41332. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41333. // check for easingFunction and correction of gradient
  41334. var easingFunction = this._animation.getEasingFunction();
  41335. if (easingFunction != null) {
  41336. gradient = easingFunction.ease(gradient);
  41337. }
  41338. switch (this._animation.dataType) {
  41339. // Float
  41340. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41341. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41342. switch (loopMode) {
  41343. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41344. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41345. return floatValue;
  41346. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41347. return offsetValue * repeatCount + floatValue;
  41348. }
  41349. break;
  41350. // Quaternion
  41351. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41352. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41353. switch (loopMode) {
  41354. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41355. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41356. return quatValue;
  41357. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41358. return quatValue.add(offsetValue.scale(repeatCount));
  41359. }
  41360. return quatValue;
  41361. // Vector3
  41362. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41363. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41364. switch (loopMode) {
  41365. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41366. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41367. return vec3Value;
  41368. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41369. return vec3Value.add(offsetValue.scale(repeatCount));
  41370. }
  41371. // Vector2
  41372. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41373. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41374. switch (loopMode) {
  41375. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41376. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41377. return vec2Value;
  41378. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41379. return vec2Value.add(offsetValue.scale(repeatCount));
  41380. }
  41381. // Size
  41382. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41383. switch (loopMode) {
  41384. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41385. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41386. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41387. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41388. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41389. }
  41390. // Color3
  41391. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41392. switch (loopMode) {
  41393. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41394. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41395. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41396. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41397. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41398. }
  41399. // Matrix
  41400. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41401. switch (loopMode) {
  41402. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41403. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41404. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41405. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41406. }
  41407. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41408. return startValue;
  41409. }
  41410. default:
  41411. break;
  41412. }
  41413. break;
  41414. }
  41415. }
  41416. return this._getKeyValue(keys[keys.length - 1].value);
  41417. };
  41418. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41419. if (blend === void 0) { blend = false; }
  41420. // Set value
  41421. var path;
  41422. var destination;
  41423. var targetPropertyPath = this._animation.targetPropertyPath;
  41424. if (targetPropertyPath.length > 1) {
  41425. var property = this._target[targetPropertyPath[0]];
  41426. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41427. property = property[targetPropertyPath[index]];
  41428. }
  41429. path = targetPropertyPath[targetPropertyPath.length - 1];
  41430. destination = property;
  41431. }
  41432. else {
  41433. path = targetPropertyPath[0];
  41434. destination = this._target;
  41435. }
  41436. // Blending
  41437. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41438. if (!this._originalBlendValue) {
  41439. if (destination[path].clone) {
  41440. this._originalBlendValue = destination[path].clone();
  41441. }
  41442. else {
  41443. this._originalBlendValue = destination[path];
  41444. }
  41445. }
  41446. if (this._originalBlendValue.prototype) {
  41447. if (this._originalBlendValue.prototype.Lerp) {
  41448. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41449. }
  41450. else {
  41451. destination[path] = currentValue;
  41452. }
  41453. }
  41454. else if (this._originalBlendValue.m) {
  41455. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41456. }
  41457. else {
  41458. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41459. }
  41460. this._blendingFactor += this._animation.blendingSpeed;
  41461. }
  41462. else {
  41463. destination[path] = currentValue;
  41464. }
  41465. if (this._target.markAsDirty) {
  41466. this._target.markAsDirty(this._animation.targetProperty);
  41467. }
  41468. };
  41469. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41470. var keys = this._animation.getKeys();
  41471. if (frame < keys[0].frame) {
  41472. frame = keys[0].frame;
  41473. }
  41474. else if (frame > keys[keys.length - 1].frame) {
  41475. frame = keys[keys.length - 1].frame;
  41476. }
  41477. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41478. this.setValue(currentValue);
  41479. };
  41480. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41481. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41482. this._ratioOffset = this._previousRatio - newRatio;
  41483. };
  41484. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41485. if (blend === void 0) { blend = false; }
  41486. var targetPropertyPath = this._animation.targetPropertyPath;
  41487. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41488. this._stopped = true;
  41489. return false;
  41490. }
  41491. var returnValue = true;
  41492. var keys = this._animation.getKeys();
  41493. // Adding a start key at frame 0 if missing
  41494. if (keys[0].frame !== 0) {
  41495. var newKey = { frame: 0, value: keys[0].value };
  41496. keys.splice(0, 0, newKey);
  41497. }
  41498. // Check limits
  41499. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41500. from = keys[0].frame;
  41501. }
  41502. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41503. to = keys[keys.length - 1].frame;
  41504. }
  41505. //to and from cannot be the same key
  41506. if (from === to) {
  41507. if (from > keys[0].frame) {
  41508. from--;
  41509. }
  41510. else if (to < keys[keys.length - 1].frame) {
  41511. to++;
  41512. }
  41513. }
  41514. // Compute ratio
  41515. var range = to - from;
  41516. var offsetValue;
  41517. // ratio represents the frame delta between from and to
  41518. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41519. var highLimitValue = 0;
  41520. this._previousDelay = delay;
  41521. this._previousRatio = ratio;
  41522. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41523. returnValue = false;
  41524. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41525. }
  41526. else {
  41527. // Get max value if required
  41528. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41529. var keyOffset = to.toString() + from.toString();
  41530. if (!this._offsetsCache[keyOffset]) {
  41531. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41532. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41533. switch (this._animation.dataType) {
  41534. // Float
  41535. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41536. this._offsetsCache[keyOffset] = toValue - fromValue;
  41537. break;
  41538. // Quaternion
  41539. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41540. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41541. break;
  41542. // Vector3
  41543. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41544. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41545. // Vector2
  41546. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41547. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41548. // Size
  41549. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41550. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41551. // Color3
  41552. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41553. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41554. default:
  41555. break;
  41556. }
  41557. this._highLimitsCache[keyOffset] = toValue;
  41558. }
  41559. highLimitValue = this._highLimitsCache[keyOffset];
  41560. offsetValue = this._offsetsCache[keyOffset];
  41561. }
  41562. }
  41563. if (offsetValue === undefined) {
  41564. switch (this._animation.dataType) {
  41565. // Float
  41566. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41567. offsetValue = 0;
  41568. break;
  41569. // Quaternion
  41570. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41571. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41572. break;
  41573. // Vector3
  41574. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41575. offsetValue = BABYLON.Vector3.Zero();
  41576. break;
  41577. // Vector2
  41578. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41579. offsetValue = BABYLON.Vector2.Zero();
  41580. break;
  41581. // Size
  41582. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41583. offsetValue = BABYLON.Size.Zero();
  41584. break;
  41585. // Color3
  41586. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41587. offsetValue = BABYLON.Color3.Black();
  41588. }
  41589. }
  41590. // Compute value
  41591. var repeatCount = (ratio / range) >> 0;
  41592. var currentFrame = returnValue ? from + ratio % range : to;
  41593. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41594. // Set value
  41595. this.setValue(currentValue);
  41596. // Check events
  41597. var events = this._animation.getEvents();
  41598. for (var index = 0; index < events.length; index++) {
  41599. // Make sure current frame has passed event frame and that event frame is within the current range
  41600. // Also, handle both forward and reverse animations
  41601. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41602. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41603. var event = events[index];
  41604. if (!event.isDone) {
  41605. // If event should be done only once, remove it.
  41606. if (event.onlyOnce) {
  41607. events.splice(index, 1);
  41608. index--;
  41609. }
  41610. event.isDone = true;
  41611. event.action();
  41612. } // Don't do anything if the event has already be done.
  41613. }
  41614. else if (events[index].isDone && !events[index].onlyOnce) {
  41615. // reset event, the animation is looping
  41616. events[index].isDone = false;
  41617. }
  41618. }
  41619. if (!returnValue) {
  41620. this._stopped = true;
  41621. }
  41622. return returnValue;
  41623. };
  41624. return RuntimeAnimation;
  41625. }());
  41626. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41627. })(BABYLON || (BABYLON = {}));
  41628. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41629. var BABYLON;
  41630. (function (BABYLON) {
  41631. var Animatable = /** @class */ (function () {
  41632. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41633. if (fromFrame === void 0) { fromFrame = 0; }
  41634. if (toFrame === void 0) { toFrame = 100; }
  41635. if (loopAnimation === void 0) { loopAnimation = false; }
  41636. if (speedRatio === void 0) { speedRatio = 1.0; }
  41637. this.target = target;
  41638. this.fromFrame = fromFrame;
  41639. this.toFrame = toFrame;
  41640. this.loopAnimation = loopAnimation;
  41641. this.onAnimationEnd = onAnimationEnd;
  41642. this._localDelayOffset = null;
  41643. this._pausedDelay = null;
  41644. this._runtimeAnimations = new Array();
  41645. this._paused = false;
  41646. this._speedRatio = 1;
  41647. this.animationStarted = false;
  41648. if (animations) {
  41649. this.appendAnimations(target, animations);
  41650. }
  41651. this._speedRatio = speedRatio;
  41652. this._scene = scene;
  41653. scene._activeAnimatables.push(this);
  41654. }
  41655. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41656. get: function () {
  41657. return this._speedRatio;
  41658. },
  41659. set: function (value) {
  41660. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41661. var animation = this._runtimeAnimations[index];
  41662. animation._prepareForSpeedRatioChange(value);
  41663. }
  41664. this._speedRatio = value;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. // Methods
  41670. Animatable.prototype.getAnimations = function () {
  41671. return this._runtimeAnimations;
  41672. };
  41673. Animatable.prototype.appendAnimations = function (target, animations) {
  41674. for (var index = 0; index < animations.length; index++) {
  41675. var animation = animations[index];
  41676. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41677. }
  41678. };
  41679. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41680. var runtimeAnimations = this._runtimeAnimations;
  41681. for (var index = 0; index < runtimeAnimations.length; index++) {
  41682. if (runtimeAnimations[index].animation.targetProperty === property) {
  41683. return runtimeAnimations[index].animation;
  41684. }
  41685. }
  41686. return null;
  41687. };
  41688. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41689. var runtimeAnimations = this._runtimeAnimations;
  41690. for (var index = 0; index < runtimeAnimations.length; index++) {
  41691. if (runtimeAnimations[index].animation.targetProperty === property) {
  41692. return runtimeAnimations[index];
  41693. }
  41694. }
  41695. return null;
  41696. };
  41697. Animatable.prototype.reset = function () {
  41698. var runtimeAnimations = this._runtimeAnimations;
  41699. for (var index = 0; index < runtimeAnimations.length; index++) {
  41700. runtimeAnimations[index].reset();
  41701. }
  41702. this._localDelayOffset = null;
  41703. this._pausedDelay = null;
  41704. };
  41705. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41706. var runtimeAnimations = this._runtimeAnimations;
  41707. for (var index = 0; index < runtimeAnimations.length; index++) {
  41708. runtimeAnimations[index].animation.enableBlending = true;
  41709. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41710. }
  41711. };
  41712. Animatable.prototype.disableBlending = function () {
  41713. var runtimeAnimations = this._runtimeAnimations;
  41714. for (var index = 0; index < runtimeAnimations.length; index++) {
  41715. runtimeAnimations[index].animation.enableBlending = false;
  41716. }
  41717. };
  41718. Animatable.prototype.goToFrame = function (frame) {
  41719. var runtimeAnimations = this._runtimeAnimations;
  41720. if (runtimeAnimations[0]) {
  41721. var fps = runtimeAnimations[0].animation.framePerSecond;
  41722. var currentFrame = runtimeAnimations[0].currentFrame;
  41723. var adjustTime = frame - currentFrame;
  41724. var delay = adjustTime * 1000 / fps;
  41725. if (this._localDelayOffset === null) {
  41726. this._localDelayOffset = 0;
  41727. }
  41728. this._localDelayOffset -= delay;
  41729. }
  41730. for (var index = 0; index < runtimeAnimations.length; index++) {
  41731. runtimeAnimations[index].goToFrame(frame);
  41732. }
  41733. };
  41734. Animatable.prototype.pause = function () {
  41735. if (this._paused) {
  41736. return;
  41737. }
  41738. this._paused = true;
  41739. };
  41740. Animatable.prototype.restart = function () {
  41741. this._paused = false;
  41742. };
  41743. Animatable.prototype.stop = function (animationName) {
  41744. if (animationName) {
  41745. var idx = this._scene._activeAnimatables.indexOf(this);
  41746. if (idx > -1) {
  41747. var runtimeAnimations = this._runtimeAnimations;
  41748. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41749. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41750. continue;
  41751. }
  41752. runtimeAnimations[index].dispose();
  41753. runtimeAnimations.splice(index, 1);
  41754. }
  41755. if (runtimeAnimations.length == 0) {
  41756. this._scene._activeAnimatables.splice(idx, 1);
  41757. if (this.onAnimationEnd) {
  41758. this.onAnimationEnd();
  41759. }
  41760. }
  41761. }
  41762. }
  41763. else {
  41764. var index = this._scene._activeAnimatables.indexOf(this);
  41765. if (index > -1) {
  41766. this._scene._activeAnimatables.splice(index, 1);
  41767. var runtimeAnimations = this._runtimeAnimations;
  41768. for (var index = 0; index < runtimeAnimations.length; index++) {
  41769. runtimeAnimations[index].dispose();
  41770. }
  41771. if (this.onAnimationEnd) {
  41772. this.onAnimationEnd();
  41773. }
  41774. }
  41775. }
  41776. };
  41777. Animatable.prototype._animate = function (delay) {
  41778. if (this._paused) {
  41779. this.animationStarted = false;
  41780. if (this._pausedDelay === null) {
  41781. this._pausedDelay = delay;
  41782. }
  41783. return true;
  41784. }
  41785. if (this._localDelayOffset === null) {
  41786. this._localDelayOffset = delay;
  41787. }
  41788. else if (this._pausedDelay !== null) {
  41789. this._localDelayOffset += delay - this._pausedDelay;
  41790. this._pausedDelay = null;
  41791. }
  41792. // Animating
  41793. var running = false;
  41794. var runtimeAnimations = this._runtimeAnimations;
  41795. var index;
  41796. for (index = 0; index < runtimeAnimations.length; index++) {
  41797. var animation = runtimeAnimations[index];
  41798. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41799. running = running || isRunning;
  41800. }
  41801. this.animationStarted = running;
  41802. if (!running) {
  41803. // Remove from active animatables
  41804. index = this._scene._activeAnimatables.indexOf(this);
  41805. this._scene._activeAnimatables.splice(index, 1);
  41806. // Dispose all runtime animations
  41807. for (index = 0; index < runtimeAnimations.length; index++) {
  41808. runtimeAnimations[index].dispose();
  41809. }
  41810. }
  41811. if (!running && this.onAnimationEnd) {
  41812. this.onAnimationEnd();
  41813. this.onAnimationEnd = null;
  41814. }
  41815. return running;
  41816. };
  41817. return Animatable;
  41818. }());
  41819. BABYLON.Animatable = Animatable;
  41820. })(BABYLON || (BABYLON = {}));
  41821. //# sourceMappingURL=babylon.animatable.js.map
  41822. var BABYLON;
  41823. (function (BABYLON) {
  41824. var EasingFunction = /** @class */ (function () {
  41825. function EasingFunction() {
  41826. // Properties
  41827. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41828. }
  41829. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41830. get: function () {
  41831. return EasingFunction._EASINGMODE_EASEIN;
  41832. },
  41833. enumerable: true,
  41834. configurable: true
  41835. });
  41836. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41837. get: function () {
  41838. return EasingFunction._EASINGMODE_EASEOUT;
  41839. },
  41840. enumerable: true,
  41841. configurable: true
  41842. });
  41843. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41844. get: function () {
  41845. return EasingFunction._EASINGMODE_EASEINOUT;
  41846. },
  41847. enumerable: true,
  41848. configurable: true
  41849. });
  41850. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41851. var n = Math.min(Math.max(easingMode, 0), 2);
  41852. this._easingMode = n;
  41853. };
  41854. EasingFunction.prototype.getEasingMode = function () {
  41855. return this._easingMode;
  41856. };
  41857. EasingFunction.prototype.easeInCore = function (gradient) {
  41858. throw new Error('You must implement this method');
  41859. };
  41860. EasingFunction.prototype.ease = function (gradient) {
  41861. switch (this._easingMode) {
  41862. case EasingFunction.EASINGMODE_EASEIN:
  41863. return this.easeInCore(gradient);
  41864. case EasingFunction.EASINGMODE_EASEOUT:
  41865. return (1 - this.easeInCore(1 - gradient));
  41866. }
  41867. if (gradient >= 0.5) {
  41868. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41869. }
  41870. return (this.easeInCore(gradient * 2) * 0.5);
  41871. };
  41872. //Statics
  41873. EasingFunction._EASINGMODE_EASEIN = 0;
  41874. EasingFunction._EASINGMODE_EASEOUT = 1;
  41875. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41876. return EasingFunction;
  41877. }());
  41878. BABYLON.EasingFunction = EasingFunction;
  41879. var CircleEase = /** @class */ (function (_super) {
  41880. __extends(CircleEase, _super);
  41881. function CircleEase() {
  41882. return _super !== null && _super.apply(this, arguments) || this;
  41883. }
  41884. CircleEase.prototype.easeInCore = function (gradient) {
  41885. gradient = Math.max(0, Math.min(1, gradient));
  41886. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41887. };
  41888. return CircleEase;
  41889. }(EasingFunction));
  41890. BABYLON.CircleEase = CircleEase;
  41891. var BackEase = /** @class */ (function (_super) {
  41892. __extends(BackEase, _super);
  41893. function BackEase(amplitude) {
  41894. if (amplitude === void 0) { amplitude = 1; }
  41895. var _this = _super.call(this) || this;
  41896. _this.amplitude = amplitude;
  41897. return _this;
  41898. }
  41899. BackEase.prototype.easeInCore = function (gradient) {
  41900. var num = Math.max(0, this.amplitude);
  41901. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41902. };
  41903. return BackEase;
  41904. }(EasingFunction));
  41905. BABYLON.BackEase = BackEase;
  41906. var BounceEase = /** @class */ (function (_super) {
  41907. __extends(BounceEase, _super);
  41908. function BounceEase(bounces, bounciness) {
  41909. if (bounces === void 0) { bounces = 3; }
  41910. if (bounciness === void 0) { bounciness = 2; }
  41911. var _this = _super.call(this) || this;
  41912. _this.bounces = bounces;
  41913. _this.bounciness = bounciness;
  41914. return _this;
  41915. }
  41916. BounceEase.prototype.easeInCore = function (gradient) {
  41917. var y = Math.max(0.0, this.bounces);
  41918. var bounciness = this.bounciness;
  41919. if (bounciness <= 1.0) {
  41920. bounciness = 1.001;
  41921. }
  41922. var num9 = Math.pow(bounciness, y);
  41923. var num5 = 1.0 - bounciness;
  41924. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41925. var num15 = gradient * num4;
  41926. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41927. var num3 = Math.floor(num65);
  41928. var num13 = num3 + 1.0;
  41929. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41930. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41931. var num7 = (num8 + num12) * 0.5;
  41932. var num6 = gradient - num7;
  41933. var num2 = num7 - num8;
  41934. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41935. };
  41936. return BounceEase;
  41937. }(EasingFunction));
  41938. BABYLON.BounceEase = BounceEase;
  41939. var CubicEase = /** @class */ (function (_super) {
  41940. __extends(CubicEase, _super);
  41941. function CubicEase() {
  41942. return _super !== null && _super.apply(this, arguments) || this;
  41943. }
  41944. CubicEase.prototype.easeInCore = function (gradient) {
  41945. return (gradient * gradient * gradient);
  41946. };
  41947. return CubicEase;
  41948. }(EasingFunction));
  41949. BABYLON.CubicEase = CubicEase;
  41950. var ElasticEase = /** @class */ (function (_super) {
  41951. __extends(ElasticEase, _super);
  41952. function ElasticEase(oscillations, springiness) {
  41953. if (oscillations === void 0) { oscillations = 3; }
  41954. if (springiness === void 0) { springiness = 3; }
  41955. var _this = _super.call(this) || this;
  41956. _this.oscillations = oscillations;
  41957. _this.springiness = springiness;
  41958. return _this;
  41959. }
  41960. ElasticEase.prototype.easeInCore = function (gradient) {
  41961. var num2;
  41962. var num3 = Math.max(0.0, this.oscillations);
  41963. var num = Math.max(0.0, this.springiness);
  41964. if (num == 0) {
  41965. num2 = gradient;
  41966. }
  41967. else {
  41968. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41969. }
  41970. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41971. };
  41972. return ElasticEase;
  41973. }(EasingFunction));
  41974. BABYLON.ElasticEase = ElasticEase;
  41975. var ExponentialEase = /** @class */ (function (_super) {
  41976. __extends(ExponentialEase, _super);
  41977. function ExponentialEase(exponent) {
  41978. if (exponent === void 0) { exponent = 2; }
  41979. var _this = _super.call(this) || this;
  41980. _this.exponent = exponent;
  41981. return _this;
  41982. }
  41983. ExponentialEase.prototype.easeInCore = function (gradient) {
  41984. if (this.exponent <= 0) {
  41985. return gradient;
  41986. }
  41987. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41988. };
  41989. return ExponentialEase;
  41990. }(EasingFunction));
  41991. BABYLON.ExponentialEase = ExponentialEase;
  41992. var PowerEase = /** @class */ (function (_super) {
  41993. __extends(PowerEase, _super);
  41994. function PowerEase(power) {
  41995. if (power === void 0) { power = 2; }
  41996. var _this = _super.call(this) || this;
  41997. _this.power = power;
  41998. return _this;
  41999. }
  42000. PowerEase.prototype.easeInCore = function (gradient) {
  42001. var y = Math.max(0.0, this.power);
  42002. return Math.pow(gradient, y);
  42003. };
  42004. return PowerEase;
  42005. }(EasingFunction));
  42006. BABYLON.PowerEase = PowerEase;
  42007. var QuadraticEase = /** @class */ (function (_super) {
  42008. __extends(QuadraticEase, _super);
  42009. function QuadraticEase() {
  42010. return _super !== null && _super.apply(this, arguments) || this;
  42011. }
  42012. QuadraticEase.prototype.easeInCore = function (gradient) {
  42013. return (gradient * gradient);
  42014. };
  42015. return QuadraticEase;
  42016. }(EasingFunction));
  42017. BABYLON.QuadraticEase = QuadraticEase;
  42018. var QuarticEase = /** @class */ (function (_super) {
  42019. __extends(QuarticEase, _super);
  42020. function QuarticEase() {
  42021. return _super !== null && _super.apply(this, arguments) || this;
  42022. }
  42023. QuarticEase.prototype.easeInCore = function (gradient) {
  42024. return (gradient * gradient * gradient * gradient);
  42025. };
  42026. return QuarticEase;
  42027. }(EasingFunction));
  42028. BABYLON.QuarticEase = QuarticEase;
  42029. var QuinticEase = /** @class */ (function (_super) {
  42030. __extends(QuinticEase, _super);
  42031. function QuinticEase() {
  42032. return _super !== null && _super.apply(this, arguments) || this;
  42033. }
  42034. QuinticEase.prototype.easeInCore = function (gradient) {
  42035. return (gradient * gradient * gradient * gradient * gradient);
  42036. };
  42037. return QuinticEase;
  42038. }(EasingFunction));
  42039. BABYLON.QuinticEase = QuinticEase;
  42040. var SineEase = /** @class */ (function (_super) {
  42041. __extends(SineEase, _super);
  42042. function SineEase() {
  42043. return _super !== null && _super.apply(this, arguments) || this;
  42044. }
  42045. SineEase.prototype.easeInCore = function (gradient) {
  42046. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42047. };
  42048. return SineEase;
  42049. }(EasingFunction));
  42050. BABYLON.SineEase = SineEase;
  42051. var BezierCurveEase = /** @class */ (function (_super) {
  42052. __extends(BezierCurveEase, _super);
  42053. function BezierCurveEase(x1, y1, x2, y2) {
  42054. if (x1 === void 0) { x1 = 0; }
  42055. if (y1 === void 0) { y1 = 0; }
  42056. if (x2 === void 0) { x2 = 1; }
  42057. if (y2 === void 0) { y2 = 1; }
  42058. var _this = _super.call(this) || this;
  42059. _this.x1 = x1;
  42060. _this.y1 = y1;
  42061. _this.x2 = x2;
  42062. _this.y2 = y2;
  42063. return _this;
  42064. }
  42065. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42066. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42067. };
  42068. return BezierCurveEase;
  42069. }(EasingFunction));
  42070. BABYLON.BezierCurveEase = BezierCurveEase;
  42071. })(BABYLON || (BABYLON = {}));
  42072. //# sourceMappingURL=babylon.easing.js.map
  42073. var BABYLON;
  42074. (function (BABYLON) {
  42075. var Condition = /** @class */ (function () {
  42076. function Condition(actionManager) {
  42077. this._actionManager = actionManager;
  42078. }
  42079. Condition.prototype.isValid = function () {
  42080. return true;
  42081. };
  42082. Condition.prototype._getProperty = function (propertyPath) {
  42083. return this._actionManager._getProperty(propertyPath);
  42084. };
  42085. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42086. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42087. };
  42088. Condition.prototype.serialize = function () {
  42089. };
  42090. Condition.prototype._serialize = function (serializedCondition) {
  42091. return {
  42092. type: 2,
  42093. children: [],
  42094. name: serializedCondition.name,
  42095. properties: serializedCondition.properties
  42096. };
  42097. };
  42098. return Condition;
  42099. }());
  42100. BABYLON.Condition = Condition;
  42101. var ValueCondition = /** @class */ (function (_super) {
  42102. __extends(ValueCondition, _super);
  42103. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42104. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42105. var _this = _super.call(this, actionManager) || this;
  42106. _this.propertyPath = propertyPath;
  42107. _this.value = value;
  42108. _this.operator = operator;
  42109. _this._target = target;
  42110. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42111. _this._property = _this._getProperty(_this.propertyPath);
  42112. return _this;
  42113. }
  42114. Object.defineProperty(ValueCondition, "IsEqual", {
  42115. get: function () {
  42116. return ValueCondition._IsEqual;
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. Object.defineProperty(ValueCondition, "IsDifferent", {
  42122. get: function () {
  42123. return ValueCondition._IsDifferent;
  42124. },
  42125. enumerable: true,
  42126. configurable: true
  42127. });
  42128. Object.defineProperty(ValueCondition, "IsGreater", {
  42129. get: function () {
  42130. return ValueCondition._IsGreater;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. Object.defineProperty(ValueCondition, "IsLesser", {
  42136. get: function () {
  42137. return ValueCondition._IsLesser;
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. // Methods
  42143. ValueCondition.prototype.isValid = function () {
  42144. switch (this.operator) {
  42145. case ValueCondition.IsGreater:
  42146. return this._effectiveTarget[this._property] > this.value;
  42147. case ValueCondition.IsLesser:
  42148. return this._effectiveTarget[this._property] < this.value;
  42149. case ValueCondition.IsEqual:
  42150. case ValueCondition.IsDifferent:
  42151. var check;
  42152. if (this.value.equals) {
  42153. check = this.value.equals(this._effectiveTarget[this._property]);
  42154. }
  42155. else {
  42156. check = this.value === this._effectiveTarget[this._property];
  42157. }
  42158. return this.operator === ValueCondition.IsEqual ? check : !check;
  42159. }
  42160. return false;
  42161. };
  42162. ValueCondition.prototype.serialize = function () {
  42163. return this._serialize({
  42164. name: "ValueCondition",
  42165. properties: [
  42166. BABYLON.Action._GetTargetProperty(this._target),
  42167. { name: "propertyPath", value: this.propertyPath },
  42168. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42169. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42170. ]
  42171. });
  42172. };
  42173. ValueCondition.GetOperatorName = function (operator) {
  42174. switch (operator) {
  42175. case ValueCondition._IsEqual: return "IsEqual";
  42176. case ValueCondition._IsDifferent: return "IsDifferent";
  42177. case ValueCondition._IsGreater: return "IsGreater";
  42178. case ValueCondition._IsLesser: return "IsLesser";
  42179. default: return "";
  42180. }
  42181. };
  42182. // Statics
  42183. ValueCondition._IsEqual = 0;
  42184. ValueCondition._IsDifferent = 1;
  42185. ValueCondition._IsGreater = 2;
  42186. ValueCondition._IsLesser = 3;
  42187. return ValueCondition;
  42188. }(Condition));
  42189. BABYLON.ValueCondition = ValueCondition;
  42190. var PredicateCondition = /** @class */ (function (_super) {
  42191. __extends(PredicateCondition, _super);
  42192. function PredicateCondition(actionManager, predicate) {
  42193. var _this = _super.call(this, actionManager) || this;
  42194. _this.predicate = predicate;
  42195. return _this;
  42196. }
  42197. PredicateCondition.prototype.isValid = function () {
  42198. return this.predicate();
  42199. };
  42200. return PredicateCondition;
  42201. }(Condition));
  42202. BABYLON.PredicateCondition = PredicateCondition;
  42203. var StateCondition = /** @class */ (function (_super) {
  42204. __extends(StateCondition, _super);
  42205. function StateCondition(actionManager, target, value) {
  42206. var _this = _super.call(this, actionManager) || this;
  42207. _this.value = value;
  42208. _this._target = target;
  42209. return _this;
  42210. }
  42211. // Methods
  42212. StateCondition.prototype.isValid = function () {
  42213. return this._target.state === this.value;
  42214. };
  42215. StateCondition.prototype.serialize = function () {
  42216. return this._serialize({
  42217. name: "StateCondition",
  42218. properties: [
  42219. BABYLON.Action._GetTargetProperty(this._target),
  42220. { name: "value", value: this.value }
  42221. ]
  42222. });
  42223. };
  42224. return StateCondition;
  42225. }(Condition));
  42226. BABYLON.StateCondition = StateCondition;
  42227. })(BABYLON || (BABYLON = {}));
  42228. //# sourceMappingURL=babylon.condition.js.map
  42229. var BABYLON;
  42230. (function (BABYLON) {
  42231. var Action = /** @class */ (function () {
  42232. function Action(triggerOptions, condition) {
  42233. this.triggerOptions = triggerOptions;
  42234. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42235. if (triggerOptions.parameter) {
  42236. this.trigger = triggerOptions.trigger;
  42237. this._triggerParameter = triggerOptions.parameter;
  42238. }
  42239. else {
  42240. this.trigger = triggerOptions;
  42241. }
  42242. this._nextActiveAction = this;
  42243. this._condition = condition;
  42244. }
  42245. // Methods
  42246. Action.prototype._prepare = function () {
  42247. };
  42248. Action.prototype.getTriggerParameter = function () {
  42249. return this._triggerParameter;
  42250. };
  42251. Action.prototype._executeCurrent = function (evt) {
  42252. if (this._nextActiveAction._condition) {
  42253. var condition = this._nextActiveAction._condition;
  42254. var currentRenderId = this._actionManager.getScene().getRenderId();
  42255. // We cache the current evaluation for the current frame
  42256. if (condition._evaluationId === currentRenderId) {
  42257. if (!condition._currentResult) {
  42258. return;
  42259. }
  42260. }
  42261. else {
  42262. condition._evaluationId = currentRenderId;
  42263. if (!condition.isValid()) {
  42264. condition._currentResult = false;
  42265. return;
  42266. }
  42267. condition._currentResult = true;
  42268. }
  42269. }
  42270. this.onBeforeExecuteObservable.notifyObservers(this);
  42271. this._nextActiveAction.execute(evt);
  42272. this.skipToNextActiveAction();
  42273. };
  42274. Action.prototype.execute = function (evt) {
  42275. };
  42276. Action.prototype.skipToNextActiveAction = function () {
  42277. if (this._nextActiveAction._child) {
  42278. if (!this._nextActiveAction._child._actionManager) {
  42279. this._nextActiveAction._child._actionManager = this._actionManager;
  42280. }
  42281. this._nextActiveAction = this._nextActiveAction._child;
  42282. }
  42283. else {
  42284. this._nextActiveAction = this;
  42285. }
  42286. };
  42287. Action.prototype.then = function (action) {
  42288. this._child = action;
  42289. action._actionManager = this._actionManager;
  42290. action._prepare();
  42291. return action;
  42292. };
  42293. Action.prototype._getProperty = function (propertyPath) {
  42294. return this._actionManager._getProperty(propertyPath);
  42295. };
  42296. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42297. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42298. };
  42299. Action.prototype.serialize = function (parent) {
  42300. };
  42301. // Called by BABYLON.Action objects in serialize(...). Internal use
  42302. Action.prototype._serialize = function (serializedAction, parent) {
  42303. var serializationObject = {
  42304. type: 1,
  42305. children: [],
  42306. name: serializedAction.name,
  42307. properties: serializedAction.properties || []
  42308. };
  42309. // Serialize child
  42310. if (this._child) {
  42311. this._child.serialize(serializationObject);
  42312. }
  42313. // Check if "this" has a condition
  42314. if (this._condition) {
  42315. var serializedCondition = this._condition.serialize();
  42316. serializedCondition.children.push(serializationObject);
  42317. if (parent) {
  42318. parent.children.push(serializedCondition);
  42319. }
  42320. return serializedCondition;
  42321. }
  42322. if (parent) {
  42323. parent.children.push(serializationObject);
  42324. }
  42325. return serializationObject;
  42326. };
  42327. Action._SerializeValueAsString = function (value) {
  42328. if (typeof value === "number") {
  42329. return value.toString();
  42330. }
  42331. if (typeof value === "boolean") {
  42332. return value ? "true" : "false";
  42333. }
  42334. if (value instanceof BABYLON.Vector2) {
  42335. return value.x + ", " + value.y;
  42336. }
  42337. if (value instanceof BABYLON.Vector3) {
  42338. return value.x + ", " + value.y + ", " + value.z;
  42339. }
  42340. if (value instanceof BABYLON.Color3) {
  42341. return value.r + ", " + value.g + ", " + value.b;
  42342. }
  42343. if (value instanceof BABYLON.Color4) {
  42344. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42345. }
  42346. return value; // string
  42347. };
  42348. Action._GetTargetProperty = function (target) {
  42349. return {
  42350. name: "target",
  42351. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42352. : target instanceof BABYLON.Light ? "LightProperties"
  42353. : target instanceof BABYLON.Camera ? "CameraProperties"
  42354. : "SceneProperties",
  42355. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42356. };
  42357. };
  42358. return Action;
  42359. }());
  42360. BABYLON.Action = Action;
  42361. })(BABYLON || (BABYLON = {}));
  42362. //# sourceMappingURL=babylon.action.js.map
  42363. var BABYLON;
  42364. (function (BABYLON) {
  42365. /**
  42366. * ActionEvent is the event beint sent when an action is triggered.
  42367. */
  42368. var ActionEvent = /** @class */ (function () {
  42369. /**
  42370. * @param source The mesh or sprite that triggered the action.
  42371. * @param pointerX The X mouse cursor position at the time of the event
  42372. * @param pointerY The Y mouse cursor position at the time of the event
  42373. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42374. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42375. */
  42376. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42377. this.source = source;
  42378. this.pointerX = pointerX;
  42379. this.pointerY = pointerY;
  42380. this.meshUnderPointer = meshUnderPointer;
  42381. this.sourceEvent = sourceEvent;
  42382. this.additionalData = additionalData;
  42383. }
  42384. /**
  42385. * Helper function to auto-create an ActionEvent from a source mesh.
  42386. * @param source The source mesh that triggered the event
  42387. * @param evt {Event} The original (browser) event
  42388. */
  42389. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42390. var scene = source.getScene();
  42391. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42392. };
  42393. /**
  42394. * Helper function to auto-create an ActionEvent from a source mesh.
  42395. * @param source The source sprite that triggered the event
  42396. * @param scene Scene associated with the sprite
  42397. * @param evt {Event} The original (browser) event
  42398. */
  42399. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42400. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42401. };
  42402. /**
  42403. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42404. * @param scene the scene where the event occurred
  42405. * @param evt {Event} The original (browser) event
  42406. */
  42407. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42408. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42409. };
  42410. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42411. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42412. };
  42413. return ActionEvent;
  42414. }());
  42415. BABYLON.ActionEvent = ActionEvent;
  42416. /**
  42417. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42418. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42419. */
  42420. var ActionManager = /** @class */ (function () {
  42421. function ActionManager(scene) {
  42422. // Members
  42423. this.actions = new Array();
  42424. this.hoverCursor = '';
  42425. this._scene = scene;
  42426. scene._actionManagers.push(this);
  42427. }
  42428. Object.defineProperty(ActionManager, "NothingTrigger", {
  42429. get: function () {
  42430. return ActionManager._NothingTrigger;
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42436. get: function () {
  42437. return ActionManager._OnPickTrigger;
  42438. },
  42439. enumerable: true,
  42440. configurable: true
  42441. });
  42442. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42443. get: function () {
  42444. return ActionManager._OnLeftPickTrigger;
  42445. },
  42446. enumerable: true,
  42447. configurable: true
  42448. });
  42449. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42450. get: function () {
  42451. return ActionManager._OnRightPickTrigger;
  42452. },
  42453. enumerable: true,
  42454. configurable: true
  42455. });
  42456. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42457. get: function () {
  42458. return ActionManager._OnCenterPickTrigger;
  42459. },
  42460. enumerable: true,
  42461. configurable: true
  42462. });
  42463. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42464. get: function () {
  42465. return ActionManager._OnPickDownTrigger;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42471. get: function () {
  42472. return ActionManager._OnDoublePickTrigger;
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42478. get: function () {
  42479. return ActionManager._OnPickUpTrigger;
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42485. /// This trigger will only be raised if you also declared a OnPickDown
  42486. get: function () {
  42487. return ActionManager._OnPickOutTrigger;
  42488. },
  42489. enumerable: true,
  42490. configurable: true
  42491. });
  42492. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42493. get: function () {
  42494. return ActionManager._OnLongPressTrigger;
  42495. },
  42496. enumerable: true,
  42497. configurable: true
  42498. });
  42499. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42500. get: function () {
  42501. return ActionManager._OnPointerOverTrigger;
  42502. },
  42503. enumerable: true,
  42504. configurable: true
  42505. });
  42506. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42507. get: function () {
  42508. return ActionManager._OnPointerOutTrigger;
  42509. },
  42510. enumerable: true,
  42511. configurable: true
  42512. });
  42513. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42514. get: function () {
  42515. return ActionManager._OnEveryFrameTrigger;
  42516. },
  42517. enumerable: true,
  42518. configurable: true
  42519. });
  42520. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42521. get: function () {
  42522. return ActionManager._OnIntersectionEnterTrigger;
  42523. },
  42524. enumerable: true,
  42525. configurable: true
  42526. });
  42527. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42528. get: function () {
  42529. return ActionManager._OnIntersectionExitTrigger;
  42530. },
  42531. enumerable: true,
  42532. configurable: true
  42533. });
  42534. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42535. get: function () {
  42536. return ActionManager._OnKeyDownTrigger;
  42537. },
  42538. enumerable: true,
  42539. configurable: true
  42540. });
  42541. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42542. get: function () {
  42543. return ActionManager._OnKeyUpTrigger;
  42544. },
  42545. enumerable: true,
  42546. configurable: true
  42547. });
  42548. // Methods
  42549. ActionManager.prototype.dispose = function () {
  42550. var index = this._scene._actionManagers.indexOf(this);
  42551. for (var i = 0; i < this.actions.length; i++) {
  42552. var action = this.actions[i];
  42553. ActionManager.Triggers[action.trigger]--;
  42554. if (ActionManager.Triggers[action.trigger] === 0) {
  42555. delete ActionManager.Triggers[action.trigger];
  42556. }
  42557. }
  42558. if (index > -1) {
  42559. this._scene._actionManagers.splice(index, 1);
  42560. }
  42561. };
  42562. ActionManager.prototype.getScene = function () {
  42563. return this._scene;
  42564. };
  42565. /**
  42566. * Does this action manager handles actions of any of the given triggers
  42567. * @param {number[]} triggers - the triggers to be tested
  42568. * @return {boolean} whether one (or more) of the triggers is handeled
  42569. */
  42570. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42571. for (var index = 0; index < this.actions.length; index++) {
  42572. var action = this.actions[index];
  42573. if (triggers.indexOf(action.trigger) > -1) {
  42574. return true;
  42575. }
  42576. }
  42577. return false;
  42578. };
  42579. /**
  42580. * Does this action manager handles actions of a given trigger
  42581. * @param {number} trigger - the trigger to be tested
  42582. * @return {boolean} whether the trigger is handeled
  42583. */
  42584. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42585. for (var index = 0; index < this.actions.length; index++) {
  42586. var action = this.actions[index];
  42587. if (action.trigger === trigger) {
  42588. return true;
  42589. }
  42590. }
  42591. return false;
  42592. };
  42593. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42594. /**
  42595. * Does this action manager has pointer triggers
  42596. * @return {boolean} whether or not it has pointer triggers
  42597. */
  42598. get: function () {
  42599. for (var index = 0; index < this.actions.length; index++) {
  42600. var action = this.actions[index];
  42601. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42602. return true;
  42603. }
  42604. }
  42605. return false;
  42606. },
  42607. enumerable: true,
  42608. configurable: true
  42609. });
  42610. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42611. /**
  42612. * Does this action manager has pick triggers
  42613. * @return {boolean} whether or not it has pick triggers
  42614. */
  42615. get: function () {
  42616. for (var index = 0; index < this.actions.length; index++) {
  42617. var action = this.actions[index];
  42618. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42619. return true;
  42620. }
  42621. }
  42622. return false;
  42623. },
  42624. enumerable: true,
  42625. configurable: true
  42626. });
  42627. Object.defineProperty(ActionManager, "HasTriggers", {
  42628. /**
  42629. * Does exist one action manager with at least one trigger
  42630. * @return {boolean} whether or not it exists one action manager with one trigger
  42631. **/
  42632. get: function () {
  42633. for (var t in ActionManager.Triggers) {
  42634. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42635. return true;
  42636. }
  42637. }
  42638. return false;
  42639. },
  42640. enumerable: true,
  42641. configurable: true
  42642. });
  42643. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42644. /**
  42645. * Does exist one action manager with at least one pick trigger
  42646. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42647. **/
  42648. get: function () {
  42649. for (var t in ActionManager.Triggers) {
  42650. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42651. var t_int = parseInt(t);
  42652. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42653. return true;
  42654. }
  42655. }
  42656. }
  42657. return false;
  42658. },
  42659. enumerable: true,
  42660. configurable: true
  42661. });
  42662. /**
  42663. * Does exist one action manager that handles actions of a given trigger
  42664. * @param {number} trigger - the trigger to be tested
  42665. * @return {boolean} whether the trigger is handeled by at least one action manager
  42666. **/
  42667. ActionManager.HasSpecificTrigger = function (trigger) {
  42668. for (var t in ActionManager.Triggers) {
  42669. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42670. var t_int = parseInt(t);
  42671. if (t_int === trigger) {
  42672. return true;
  42673. }
  42674. }
  42675. }
  42676. return false;
  42677. };
  42678. /**
  42679. * Registers an action to this action manager
  42680. * @param {BABYLON.Action} action - the action to be registered
  42681. * @return {BABYLON.Action} the action amended (prepared) after registration
  42682. */
  42683. ActionManager.prototype.registerAction = function (action) {
  42684. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42685. if (this.getScene().actionManager !== this) {
  42686. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42687. return null;
  42688. }
  42689. }
  42690. this.actions.push(action);
  42691. if (ActionManager.Triggers[action.trigger]) {
  42692. ActionManager.Triggers[action.trigger]++;
  42693. }
  42694. else {
  42695. ActionManager.Triggers[action.trigger] = 1;
  42696. }
  42697. action._actionManager = this;
  42698. action._prepare();
  42699. return action;
  42700. };
  42701. /**
  42702. * Process a specific trigger
  42703. * @param {number} trigger - the trigger to process
  42704. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42705. */
  42706. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42707. for (var index = 0; index < this.actions.length; index++) {
  42708. var action = this.actions[index];
  42709. if (action.trigger === trigger) {
  42710. if (evt) {
  42711. if (trigger === ActionManager.OnKeyUpTrigger
  42712. || trigger === ActionManager.OnKeyDownTrigger) {
  42713. var parameter = action.getTriggerParameter();
  42714. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42715. if (!parameter.toLowerCase) {
  42716. continue;
  42717. }
  42718. var lowerCase = parameter.toLowerCase();
  42719. if (lowerCase !== evt.sourceEvent.key) {
  42720. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42721. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42722. if (actualkey !== lowerCase) {
  42723. continue;
  42724. }
  42725. }
  42726. }
  42727. }
  42728. }
  42729. action._executeCurrent(evt);
  42730. }
  42731. }
  42732. };
  42733. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42734. var properties = propertyPath.split(".");
  42735. for (var index = 0; index < properties.length - 1; index++) {
  42736. target = target[properties[index]];
  42737. }
  42738. return target;
  42739. };
  42740. ActionManager.prototype._getProperty = function (propertyPath) {
  42741. var properties = propertyPath.split(".");
  42742. return properties[properties.length - 1];
  42743. };
  42744. ActionManager.prototype.serialize = function (name) {
  42745. var root = {
  42746. children: new Array(),
  42747. name: name,
  42748. type: 3,
  42749. properties: new Array() // Empty for root but required
  42750. };
  42751. for (var i = 0; i < this.actions.length; i++) {
  42752. var triggerObject = {
  42753. type: 0,
  42754. children: new Array(),
  42755. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42756. properties: new Array()
  42757. };
  42758. var triggerOptions = this.actions[i].triggerOptions;
  42759. if (triggerOptions && typeof triggerOptions !== "number") {
  42760. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42761. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42762. }
  42763. else {
  42764. var parameter = {};
  42765. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42766. if (triggerOptions.parameter.mesh) {
  42767. parameter._meshId = triggerOptions.parameter.mesh.id;
  42768. }
  42769. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42770. }
  42771. }
  42772. // Serialize child action, recursively
  42773. this.actions[i].serialize(triggerObject);
  42774. // Add serialized trigger
  42775. root.children.push(triggerObject);
  42776. }
  42777. return root;
  42778. };
  42779. ActionManager.Parse = function (parsedActions, object, scene) {
  42780. var actionManager = new BABYLON.ActionManager(scene);
  42781. if (object === null)
  42782. scene.actionManager = actionManager;
  42783. else
  42784. object.actionManager = actionManager;
  42785. // instanciate a new object
  42786. var instanciate = function (name, params) {
  42787. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42788. newInstance.constructor.apply(newInstance, params);
  42789. return newInstance;
  42790. };
  42791. var parseParameter = function (name, value, target, propertyPath) {
  42792. if (propertyPath === null) {
  42793. // String, boolean or float
  42794. var floatValue = parseFloat(value);
  42795. if (value === "true" || value === "false")
  42796. return value === "true";
  42797. else
  42798. return isNaN(floatValue) ? value : floatValue;
  42799. }
  42800. var effectiveTarget = propertyPath.split(".");
  42801. var values = value.split(",");
  42802. // Get effective Target
  42803. for (var i = 0; i < effectiveTarget.length; i++) {
  42804. target = target[effectiveTarget[i]];
  42805. }
  42806. // Return appropriate value with its type
  42807. if (typeof (target) === "boolean")
  42808. return values[0] === "true";
  42809. if (typeof (target) === "string")
  42810. return values[0];
  42811. // Parameters with multiple values such as Vector3 etc.
  42812. var split = new Array();
  42813. for (var i = 0; i < values.length; i++)
  42814. split.push(parseFloat(values[i]));
  42815. if (target instanceof BABYLON.Vector3)
  42816. return BABYLON.Vector3.FromArray(split);
  42817. if (target instanceof BABYLON.Vector4)
  42818. return BABYLON.Vector4.FromArray(split);
  42819. if (target instanceof BABYLON.Color3)
  42820. return BABYLON.Color3.FromArray(split);
  42821. if (target instanceof BABYLON.Color4)
  42822. return BABYLON.Color4.FromArray(split);
  42823. return parseFloat(values[0]);
  42824. };
  42825. // traverse graph per trigger
  42826. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42827. if (combineArray === void 0) { combineArray = null; }
  42828. if (parsedAction.detached)
  42829. return;
  42830. var parameters = new Array();
  42831. var target = null;
  42832. var propertyPath = null;
  42833. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42834. // Parameters
  42835. if (parsedAction.type === 2)
  42836. parameters.push(actionManager);
  42837. else
  42838. parameters.push(trigger);
  42839. if (combine) {
  42840. var actions = new Array();
  42841. for (var j = 0; j < parsedAction.combine.length; j++) {
  42842. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42843. }
  42844. parameters.push(actions);
  42845. }
  42846. else {
  42847. for (var i = 0; i < parsedAction.properties.length; i++) {
  42848. var value = parsedAction.properties[i].value;
  42849. var name = parsedAction.properties[i].name;
  42850. var targetType = parsedAction.properties[i].targetType;
  42851. if (name === "target")
  42852. if (targetType !== null && targetType === "SceneProperties")
  42853. value = target = scene;
  42854. else
  42855. value = target = scene.getNodeByName(value);
  42856. else if (name === "parent")
  42857. value = scene.getNodeByName(value);
  42858. else if (name === "sound")
  42859. value = scene.getSoundByName(value);
  42860. else if (name !== "propertyPath") {
  42861. if (parsedAction.type === 2 && name === "operator")
  42862. value = BABYLON.ValueCondition[value];
  42863. else
  42864. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42865. }
  42866. else {
  42867. propertyPath = value;
  42868. }
  42869. parameters.push(value);
  42870. }
  42871. }
  42872. if (combineArray === null) {
  42873. parameters.push(condition);
  42874. }
  42875. else {
  42876. parameters.push(null);
  42877. }
  42878. // If interpolate value action
  42879. if (parsedAction.name === "InterpolateValueAction") {
  42880. var param = parameters[parameters.length - 2];
  42881. parameters[parameters.length - 1] = param;
  42882. parameters[parameters.length - 2] = condition;
  42883. }
  42884. // Action or condition(s) and not CombineAction
  42885. var newAction = instanciate(parsedAction.name, parameters);
  42886. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42887. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42888. if (action)
  42889. action.then(nothing);
  42890. else
  42891. actionManager.registerAction(nothing);
  42892. action = nothing;
  42893. }
  42894. if (combineArray === null) {
  42895. if (newAction instanceof BABYLON.Condition) {
  42896. condition = newAction;
  42897. newAction = action;
  42898. }
  42899. else {
  42900. condition = null;
  42901. if (action)
  42902. action.then(newAction);
  42903. else
  42904. actionManager.registerAction(newAction);
  42905. }
  42906. }
  42907. else {
  42908. combineArray.push(newAction);
  42909. }
  42910. for (var i = 0; i < parsedAction.children.length; i++)
  42911. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42912. };
  42913. // triggers
  42914. for (var i = 0; i < parsedActions.children.length; i++) {
  42915. var triggerParams;
  42916. var trigger = parsedActions.children[i];
  42917. if (trigger.properties.length > 0) {
  42918. var param = trigger.properties[0].value;
  42919. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42920. if (value._meshId) {
  42921. value.mesh = scene.getMeshByID(value._meshId);
  42922. }
  42923. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42924. }
  42925. else
  42926. triggerParams = ActionManager[trigger.name];
  42927. for (var j = 0; j < trigger.children.length; j++) {
  42928. if (!trigger.detached)
  42929. traverse(trigger.children[j], triggerParams, null, null);
  42930. }
  42931. }
  42932. };
  42933. ActionManager.GetTriggerName = function (trigger) {
  42934. switch (trigger) {
  42935. case 0: return "NothingTrigger";
  42936. case 1: return "OnPickTrigger";
  42937. case 2: return "OnLeftPickTrigger";
  42938. case 3: return "OnRightPickTrigger";
  42939. case 4: return "OnCenterPickTrigger";
  42940. case 5: return "OnPickDownTrigger";
  42941. case 6: return "OnPickUpTrigger";
  42942. case 7: return "OnLongPressTrigger";
  42943. case 8: return "OnPointerOverTrigger";
  42944. case 9: return "OnPointerOutTrigger";
  42945. case 10: return "OnEveryFrameTrigger";
  42946. case 11: return "OnIntersectionEnterTrigger";
  42947. case 12: return "OnIntersectionExitTrigger";
  42948. case 13: return "OnKeyDownTrigger";
  42949. case 14: return "OnKeyUpTrigger";
  42950. case 15: return "OnPickOutTrigger";
  42951. default: return "";
  42952. }
  42953. };
  42954. // Statics
  42955. ActionManager._NothingTrigger = 0;
  42956. ActionManager._OnPickTrigger = 1;
  42957. ActionManager._OnLeftPickTrigger = 2;
  42958. ActionManager._OnRightPickTrigger = 3;
  42959. ActionManager._OnCenterPickTrigger = 4;
  42960. ActionManager._OnPickDownTrigger = 5;
  42961. ActionManager._OnDoublePickTrigger = 6;
  42962. ActionManager._OnPickUpTrigger = 7;
  42963. ActionManager._OnLongPressTrigger = 8;
  42964. ActionManager._OnPointerOverTrigger = 9;
  42965. ActionManager._OnPointerOutTrigger = 10;
  42966. ActionManager._OnEveryFrameTrigger = 11;
  42967. ActionManager._OnIntersectionEnterTrigger = 12;
  42968. ActionManager._OnIntersectionExitTrigger = 13;
  42969. ActionManager._OnKeyDownTrigger = 14;
  42970. ActionManager._OnKeyUpTrigger = 15;
  42971. ActionManager._OnPickOutTrigger = 16;
  42972. ActionManager.Triggers = {};
  42973. return ActionManager;
  42974. }());
  42975. BABYLON.ActionManager = ActionManager;
  42976. })(BABYLON || (BABYLON = {}));
  42977. //# sourceMappingURL=babylon.actionManager.js.map
  42978. var BABYLON;
  42979. (function (BABYLON) {
  42980. var InterpolateValueAction = /** @class */ (function (_super) {
  42981. __extends(InterpolateValueAction, _super);
  42982. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42983. if (duration === void 0) { duration = 1000; }
  42984. var _this = _super.call(this, triggerOptions, condition) || this;
  42985. _this.propertyPath = propertyPath;
  42986. _this.value = value;
  42987. _this.duration = duration;
  42988. _this.stopOtherAnimations = stopOtherAnimations;
  42989. _this.onInterpolationDone = onInterpolationDone;
  42990. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42991. _this._target = _this._effectiveTarget = target;
  42992. return _this;
  42993. }
  42994. InterpolateValueAction.prototype._prepare = function () {
  42995. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42996. this._property = this._getProperty(this.propertyPath);
  42997. };
  42998. InterpolateValueAction.prototype.execute = function () {
  42999. var _this = this;
  43000. var scene = this._actionManager.getScene();
  43001. var keys = [
  43002. {
  43003. frame: 0,
  43004. value: this._effectiveTarget[this._property]
  43005. }, {
  43006. frame: 100,
  43007. value: this.value
  43008. }
  43009. ];
  43010. var dataType;
  43011. if (typeof this.value === "number") {
  43012. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43013. }
  43014. else if (this.value instanceof BABYLON.Color3) {
  43015. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43016. }
  43017. else if (this.value instanceof BABYLON.Vector3) {
  43018. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43019. }
  43020. else if (this.value instanceof BABYLON.Matrix) {
  43021. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43022. }
  43023. else if (this.value instanceof BABYLON.Quaternion) {
  43024. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43025. }
  43026. else {
  43027. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43028. return;
  43029. }
  43030. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43031. animation.setKeys(keys);
  43032. if (this.stopOtherAnimations) {
  43033. scene.stopAnimation(this._effectiveTarget);
  43034. }
  43035. var wrapper = function () {
  43036. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43037. if (_this.onInterpolationDone) {
  43038. _this.onInterpolationDone();
  43039. }
  43040. };
  43041. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43042. };
  43043. InterpolateValueAction.prototype.serialize = function (parent) {
  43044. return _super.prototype._serialize.call(this, {
  43045. name: "InterpolateValueAction",
  43046. properties: [
  43047. BABYLON.Action._GetTargetProperty(this._target),
  43048. { name: "propertyPath", value: this.propertyPath },
  43049. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43050. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43051. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43052. ]
  43053. }, parent);
  43054. };
  43055. return InterpolateValueAction;
  43056. }(BABYLON.Action));
  43057. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43058. })(BABYLON || (BABYLON = {}));
  43059. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43060. var BABYLON;
  43061. (function (BABYLON) {
  43062. var SwitchBooleanAction = /** @class */ (function (_super) {
  43063. __extends(SwitchBooleanAction, _super);
  43064. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43065. var _this = _super.call(this, triggerOptions, condition) || this;
  43066. _this.propertyPath = propertyPath;
  43067. _this._target = _this._effectiveTarget = target;
  43068. return _this;
  43069. }
  43070. SwitchBooleanAction.prototype._prepare = function () {
  43071. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43072. this._property = this._getProperty(this.propertyPath);
  43073. };
  43074. SwitchBooleanAction.prototype.execute = function () {
  43075. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43076. };
  43077. SwitchBooleanAction.prototype.serialize = function (parent) {
  43078. return _super.prototype._serialize.call(this, {
  43079. name: "SwitchBooleanAction",
  43080. properties: [
  43081. BABYLON.Action._GetTargetProperty(this._target),
  43082. { name: "propertyPath", value: this.propertyPath }
  43083. ]
  43084. }, parent);
  43085. };
  43086. return SwitchBooleanAction;
  43087. }(BABYLON.Action));
  43088. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43089. var SetStateAction = /** @class */ (function (_super) {
  43090. __extends(SetStateAction, _super);
  43091. function SetStateAction(triggerOptions, target, value, condition) {
  43092. var _this = _super.call(this, triggerOptions, condition) || this;
  43093. _this.value = value;
  43094. _this._target = target;
  43095. return _this;
  43096. }
  43097. SetStateAction.prototype.execute = function () {
  43098. this._target.state = this.value;
  43099. };
  43100. SetStateAction.prototype.serialize = function (parent) {
  43101. return _super.prototype._serialize.call(this, {
  43102. name: "SetStateAction",
  43103. properties: [
  43104. BABYLON.Action._GetTargetProperty(this._target),
  43105. { name: "value", value: this.value }
  43106. ]
  43107. }, parent);
  43108. };
  43109. return SetStateAction;
  43110. }(BABYLON.Action));
  43111. BABYLON.SetStateAction = SetStateAction;
  43112. var SetValueAction = /** @class */ (function (_super) {
  43113. __extends(SetValueAction, _super);
  43114. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43115. var _this = _super.call(this, triggerOptions, condition) || this;
  43116. _this.propertyPath = propertyPath;
  43117. _this.value = value;
  43118. _this._target = _this._effectiveTarget = target;
  43119. return _this;
  43120. }
  43121. SetValueAction.prototype._prepare = function () {
  43122. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43123. this._property = this._getProperty(this.propertyPath);
  43124. };
  43125. SetValueAction.prototype.execute = function () {
  43126. this._effectiveTarget[this._property] = this.value;
  43127. if (this._target.markAsDirty) {
  43128. this._target.markAsDirty(this._property);
  43129. }
  43130. };
  43131. SetValueAction.prototype.serialize = function (parent) {
  43132. return _super.prototype._serialize.call(this, {
  43133. name: "SetValueAction",
  43134. properties: [
  43135. BABYLON.Action._GetTargetProperty(this._target),
  43136. { name: "propertyPath", value: this.propertyPath },
  43137. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43138. ]
  43139. }, parent);
  43140. };
  43141. return SetValueAction;
  43142. }(BABYLON.Action));
  43143. BABYLON.SetValueAction = SetValueAction;
  43144. var IncrementValueAction = /** @class */ (function (_super) {
  43145. __extends(IncrementValueAction, _super);
  43146. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43147. var _this = _super.call(this, triggerOptions, condition) || this;
  43148. _this.propertyPath = propertyPath;
  43149. _this.value = value;
  43150. _this._target = _this._effectiveTarget = target;
  43151. return _this;
  43152. }
  43153. IncrementValueAction.prototype._prepare = function () {
  43154. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43155. this._property = this._getProperty(this.propertyPath);
  43156. if (typeof this._effectiveTarget[this._property] !== "number") {
  43157. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43158. }
  43159. };
  43160. IncrementValueAction.prototype.execute = function () {
  43161. this._effectiveTarget[this._property] += this.value;
  43162. if (this._target.markAsDirty) {
  43163. this._target.markAsDirty(this._property);
  43164. }
  43165. };
  43166. IncrementValueAction.prototype.serialize = function (parent) {
  43167. return _super.prototype._serialize.call(this, {
  43168. name: "IncrementValueAction",
  43169. properties: [
  43170. BABYLON.Action._GetTargetProperty(this._target),
  43171. { name: "propertyPath", value: this.propertyPath },
  43172. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43173. ]
  43174. }, parent);
  43175. };
  43176. return IncrementValueAction;
  43177. }(BABYLON.Action));
  43178. BABYLON.IncrementValueAction = IncrementValueAction;
  43179. var PlayAnimationAction = /** @class */ (function (_super) {
  43180. __extends(PlayAnimationAction, _super);
  43181. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43182. var _this = _super.call(this, triggerOptions, condition) || this;
  43183. _this.from = from;
  43184. _this.to = to;
  43185. _this.loop = loop;
  43186. _this._target = target;
  43187. return _this;
  43188. }
  43189. PlayAnimationAction.prototype._prepare = function () {
  43190. };
  43191. PlayAnimationAction.prototype.execute = function () {
  43192. var scene = this._actionManager.getScene();
  43193. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43194. };
  43195. PlayAnimationAction.prototype.serialize = function (parent) {
  43196. return _super.prototype._serialize.call(this, {
  43197. name: "PlayAnimationAction",
  43198. properties: [
  43199. BABYLON.Action._GetTargetProperty(this._target),
  43200. { name: "from", value: String(this.from) },
  43201. { name: "to", value: String(this.to) },
  43202. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43203. ]
  43204. }, parent);
  43205. };
  43206. return PlayAnimationAction;
  43207. }(BABYLON.Action));
  43208. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43209. var StopAnimationAction = /** @class */ (function (_super) {
  43210. __extends(StopAnimationAction, _super);
  43211. function StopAnimationAction(triggerOptions, target, condition) {
  43212. var _this = _super.call(this, triggerOptions, condition) || this;
  43213. _this._target = target;
  43214. return _this;
  43215. }
  43216. StopAnimationAction.prototype._prepare = function () {
  43217. };
  43218. StopAnimationAction.prototype.execute = function () {
  43219. var scene = this._actionManager.getScene();
  43220. scene.stopAnimation(this._target);
  43221. };
  43222. StopAnimationAction.prototype.serialize = function (parent) {
  43223. return _super.prototype._serialize.call(this, {
  43224. name: "StopAnimationAction",
  43225. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43226. }, parent);
  43227. };
  43228. return StopAnimationAction;
  43229. }(BABYLON.Action));
  43230. BABYLON.StopAnimationAction = StopAnimationAction;
  43231. var DoNothingAction = /** @class */ (function (_super) {
  43232. __extends(DoNothingAction, _super);
  43233. function DoNothingAction(triggerOptions, condition) {
  43234. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43235. return _super.call(this, triggerOptions, condition) || this;
  43236. }
  43237. DoNothingAction.prototype.execute = function () {
  43238. };
  43239. DoNothingAction.prototype.serialize = function (parent) {
  43240. return _super.prototype._serialize.call(this, {
  43241. name: "DoNothingAction",
  43242. properties: []
  43243. }, parent);
  43244. };
  43245. return DoNothingAction;
  43246. }(BABYLON.Action));
  43247. BABYLON.DoNothingAction = DoNothingAction;
  43248. var CombineAction = /** @class */ (function (_super) {
  43249. __extends(CombineAction, _super);
  43250. function CombineAction(triggerOptions, children, condition) {
  43251. var _this = _super.call(this, triggerOptions, condition) || this;
  43252. _this.children = children;
  43253. return _this;
  43254. }
  43255. CombineAction.prototype._prepare = function () {
  43256. for (var index = 0; index < this.children.length; index++) {
  43257. this.children[index]._actionManager = this._actionManager;
  43258. this.children[index]._prepare();
  43259. }
  43260. };
  43261. CombineAction.prototype.execute = function (evt) {
  43262. for (var index = 0; index < this.children.length; index++) {
  43263. this.children[index].execute(evt);
  43264. }
  43265. };
  43266. CombineAction.prototype.serialize = function (parent) {
  43267. var serializationObject = _super.prototype._serialize.call(this, {
  43268. name: "CombineAction",
  43269. properties: [],
  43270. combine: []
  43271. }, parent);
  43272. for (var i = 0; i < this.children.length; i++) {
  43273. serializationObject.combine.push(this.children[i].serialize(null));
  43274. }
  43275. return serializationObject;
  43276. };
  43277. return CombineAction;
  43278. }(BABYLON.Action));
  43279. BABYLON.CombineAction = CombineAction;
  43280. var ExecuteCodeAction = /** @class */ (function (_super) {
  43281. __extends(ExecuteCodeAction, _super);
  43282. function ExecuteCodeAction(triggerOptions, func, condition) {
  43283. var _this = _super.call(this, triggerOptions, condition) || this;
  43284. _this.func = func;
  43285. return _this;
  43286. }
  43287. ExecuteCodeAction.prototype.execute = function (evt) {
  43288. this.func(evt);
  43289. };
  43290. return ExecuteCodeAction;
  43291. }(BABYLON.Action));
  43292. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43293. var SetParentAction = /** @class */ (function (_super) {
  43294. __extends(SetParentAction, _super);
  43295. function SetParentAction(triggerOptions, target, parent, condition) {
  43296. var _this = _super.call(this, triggerOptions, condition) || this;
  43297. _this._target = target;
  43298. _this._parent = parent;
  43299. return _this;
  43300. }
  43301. SetParentAction.prototype._prepare = function () {
  43302. };
  43303. SetParentAction.prototype.execute = function () {
  43304. if (this._target.parent === this._parent) {
  43305. return;
  43306. }
  43307. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43308. invertParentWorldMatrix.invert();
  43309. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43310. this._target.parent = this._parent;
  43311. };
  43312. SetParentAction.prototype.serialize = function (parent) {
  43313. return _super.prototype._serialize.call(this, {
  43314. name: "SetParentAction",
  43315. properties: [
  43316. BABYLON.Action._GetTargetProperty(this._target),
  43317. BABYLON.Action._GetTargetProperty(this._parent),
  43318. ]
  43319. }, parent);
  43320. };
  43321. return SetParentAction;
  43322. }(BABYLON.Action));
  43323. BABYLON.SetParentAction = SetParentAction;
  43324. var PlaySoundAction = /** @class */ (function (_super) {
  43325. __extends(PlaySoundAction, _super);
  43326. function PlaySoundAction(triggerOptions, sound, condition) {
  43327. var _this = _super.call(this, triggerOptions, condition) || this;
  43328. _this._sound = sound;
  43329. return _this;
  43330. }
  43331. PlaySoundAction.prototype._prepare = function () {
  43332. };
  43333. PlaySoundAction.prototype.execute = function () {
  43334. if (this._sound !== undefined)
  43335. this._sound.play();
  43336. };
  43337. PlaySoundAction.prototype.serialize = function (parent) {
  43338. return _super.prototype._serialize.call(this, {
  43339. name: "PlaySoundAction",
  43340. properties: [{ name: "sound", value: this._sound.name }]
  43341. }, parent);
  43342. };
  43343. return PlaySoundAction;
  43344. }(BABYLON.Action));
  43345. BABYLON.PlaySoundAction = PlaySoundAction;
  43346. var StopSoundAction = /** @class */ (function (_super) {
  43347. __extends(StopSoundAction, _super);
  43348. function StopSoundAction(triggerOptions, sound, condition) {
  43349. var _this = _super.call(this, triggerOptions, condition) || this;
  43350. _this._sound = sound;
  43351. return _this;
  43352. }
  43353. StopSoundAction.prototype._prepare = function () {
  43354. };
  43355. StopSoundAction.prototype.execute = function () {
  43356. if (this._sound !== undefined)
  43357. this._sound.stop();
  43358. };
  43359. StopSoundAction.prototype.serialize = function (parent) {
  43360. return _super.prototype._serialize.call(this, {
  43361. name: "StopSoundAction",
  43362. properties: [{ name: "sound", value: this._sound.name }]
  43363. }, parent);
  43364. };
  43365. return StopSoundAction;
  43366. }(BABYLON.Action));
  43367. BABYLON.StopSoundAction = StopSoundAction;
  43368. })(BABYLON || (BABYLON = {}));
  43369. //# sourceMappingURL=babylon.directActions.js.map
  43370. var BABYLON;
  43371. (function (BABYLON) {
  43372. var SpriteManager = /** @class */ (function () {
  43373. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43374. if (epsilon === void 0) { epsilon = 0.01; }
  43375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43376. this.name = name;
  43377. this.sprites = new Array();
  43378. this.renderingGroupId = 0;
  43379. this.layerMask = 0x0FFFFFFF;
  43380. this.fogEnabled = true;
  43381. this.isPickable = false;
  43382. /**
  43383. * An event triggered when the manager is disposed.
  43384. * @type {BABYLON.Observable}
  43385. */
  43386. this.onDisposeObservable = new BABYLON.Observable();
  43387. this._vertexBuffers = {};
  43388. this._capacity = capacity;
  43389. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43390. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43391. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43392. if (cellSize.width && cellSize.height) {
  43393. this.cellWidth = cellSize.width;
  43394. this.cellHeight = cellSize.height;
  43395. }
  43396. else if (cellSize !== undefined) {
  43397. this.cellWidth = cellSize;
  43398. this.cellHeight = cellSize;
  43399. }
  43400. else {
  43401. return;
  43402. }
  43403. this._epsilon = epsilon;
  43404. this._scene = scene;
  43405. this._scene.spriteManagers.push(this);
  43406. var indices = [];
  43407. var index = 0;
  43408. for (var count = 0; count < capacity; count++) {
  43409. indices.push(index);
  43410. indices.push(index + 1);
  43411. indices.push(index + 2);
  43412. indices.push(index);
  43413. indices.push(index + 2);
  43414. indices.push(index + 3);
  43415. index += 4;
  43416. }
  43417. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43418. // VBO
  43419. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43420. this._vertexData = new Float32Array(capacity * 16 * 4);
  43421. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43422. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43423. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43424. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43425. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43426. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43427. this._vertexBuffers["options"] = options;
  43428. this._vertexBuffers["cellInfo"] = cellInfo;
  43429. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43430. // Effects
  43431. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43432. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43433. }
  43434. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43435. set: function (callback) {
  43436. if (this._onDisposeObserver) {
  43437. this.onDisposeObservable.remove(this._onDisposeObserver);
  43438. }
  43439. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43440. },
  43441. enumerable: true,
  43442. configurable: true
  43443. });
  43444. Object.defineProperty(SpriteManager.prototype, "texture", {
  43445. get: function () {
  43446. return this._spriteTexture;
  43447. },
  43448. set: function (value) {
  43449. this._spriteTexture = value;
  43450. },
  43451. enumerable: true,
  43452. configurable: true
  43453. });
  43454. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43455. var arrayOffset = index * 16;
  43456. if (offsetX === 0)
  43457. offsetX = this._epsilon;
  43458. else if (offsetX === 1)
  43459. offsetX = 1 - this._epsilon;
  43460. if (offsetY === 0)
  43461. offsetY = this._epsilon;
  43462. else if (offsetY === 1)
  43463. offsetY = 1 - this._epsilon;
  43464. this._vertexData[arrayOffset] = sprite.position.x;
  43465. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43466. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43467. this._vertexData[arrayOffset + 3] = sprite.angle;
  43468. this._vertexData[arrayOffset + 4] = sprite.width;
  43469. this._vertexData[arrayOffset + 5] = sprite.height;
  43470. this._vertexData[arrayOffset + 6] = offsetX;
  43471. this._vertexData[arrayOffset + 7] = offsetY;
  43472. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43473. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43474. var offset = (sprite.cellIndex / rowSize) >> 0;
  43475. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43476. this._vertexData[arrayOffset + 11] = offset;
  43477. // Color
  43478. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43479. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43480. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43481. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43482. };
  43483. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43484. var count = Math.min(this._capacity, this.sprites.length);
  43485. var min = BABYLON.Vector3.Zero();
  43486. var max = BABYLON.Vector3.Zero();
  43487. var distance = Number.MAX_VALUE;
  43488. var currentSprite = null;
  43489. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43490. var cameraView = camera.getViewMatrix();
  43491. for (var index = 0; index < count; index++) {
  43492. var sprite = this.sprites[index];
  43493. if (!sprite) {
  43494. continue;
  43495. }
  43496. if (predicate) {
  43497. if (!predicate(sprite)) {
  43498. continue;
  43499. }
  43500. }
  43501. else if (!sprite.isPickable) {
  43502. continue;
  43503. }
  43504. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43505. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43506. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43507. if (ray.intersectsBoxMinMax(min, max)) {
  43508. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43509. if (distance > currentDistance) {
  43510. distance = currentDistance;
  43511. currentSprite = sprite;
  43512. if (fastCheck) {
  43513. break;
  43514. }
  43515. }
  43516. }
  43517. }
  43518. if (currentSprite) {
  43519. var result = new BABYLON.PickingInfo();
  43520. result.hit = true;
  43521. result.pickedSprite = currentSprite;
  43522. result.distance = distance;
  43523. return result;
  43524. }
  43525. return null;
  43526. };
  43527. SpriteManager.prototype.render = function () {
  43528. // Check
  43529. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43530. return;
  43531. var engine = this._scene.getEngine();
  43532. var baseSize = this._spriteTexture.getBaseSize();
  43533. // Sprites
  43534. var deltaTime = engine.getDeltaTime();
  43535. var max = Math.min(this._capacity, this.sprites.length);
  43536. var rowSize = baseSize.width / this.cellWidth;
  43537. var offset = 0;
  43538. for (var index = 0; index < max; index++) {
  43539. var sprite = this.sprites[index];
  43540. if (!sprite) {
  43541. continue;
  43542. }
  43543. sprite._animate(deltaTime);
  43544. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43545. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43546. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43547. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43548. }
  43549. this._buffer.update(this._vertexData);
  43550. // Render
  43551. var effect = this._effectBase;
  43552. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43553. effect = this._effectFog;
  43554. }
  43555. engine.enableEffect(effect);
  43556. var viewMatrix = this._scene.getViewMatrix();
  43557. effect.setTexture("diffuseSampler", this._spriteTexture);
  43558. effect.setMatrix("view", viewMatrix);
  43559. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43560. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43561. // Fog
  43562. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43563. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43564. effect.setColor3("vFogColor", this._scene.fogColor);
  43565. }
  43566. // VBOs
  43567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43568. // Draw order
  43569. engine.setDepthFunctionToLessOrEqual();
  43570. effect.setBool("alphaTest", true);
  43571. engine.setColorWrite(false);
  43572. engine.draw(true, 0, max * 6);
  43573. engine.setColorWrite(true);
  43574. effect.setBool("alphaTest", false);
  43575. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43576. engine.draw(true, 0, max * 6);
  43577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43578. };
  43579. SpriteManager.prototype.dispose = function () {
  43580. if (this._buffer) {
  43581. this._buffer.dispose();
  43582. this._buffer = null;
  43583. }
  43584. if (this._indexBuffer) {
  43585. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43586. this._indexBuffer = null;
  43587. }
  43588. if (this._spriteTexture) {
  43589. this._spriteTexture.dispose();
  43590. this._spriteTexture = null;
  43591. }
  43592. // Remove from scene
  43593. var index = this._scene.spriteManagers.indexOf(this);
  43594. this._scene.spriteManagers.splice(index, 1);
  43595. // Callback
  43596. this.onDisposeObservable.notifyObservers(this);
  43597. this.onDisposeObservable.clear();
  43598. };
  43599. return SpriteManager;
  43600. }());
  43601. BABYLON.SpriteManager = SpriteManager;
  43602. })(BABYLON || (BABYLON = {}));
  43603. //# sourceMappingURL=babylon.spriteManager.js.map
  43604. var BABYLON;
  43605. (function (BABYLON) {
  43606. var Sprite = /** @class */ (function () {
  43607. function Sprite(name, manager) {
  43608. this.name = name;
  43609. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43610. this.width = 1.0;
  43611. this.height = 1.0;
  43612. this.angle = 0;
  43613. this.cellIndex = 0;
  43614. this.invertU = 0;
  43615. this.invertV = 0;
  43616. this.animations = new Array();
  43617. this.isPickable = false;
  43618. this._animationStarted = false;
  43619. this._loopAnimation = false;
  43620. this._fromIndex = 0;
  43621. this._toIndex = 0;
  43622. this._delay = 0;
  43623. this._direction = 1;
  43624. this._time = 0;
  43625. this._manager = manager;
  43626. this._manager.sprites.push(this);
  43627. this.position = BABYLON.Vector3.Zero();
  43628. }
  43629. Object.defineProperty(Sprite.prototype, "size", {
  43630. get: function () {
  43631. return this.width;
  43632. },
  43633. set: function (value) {
  43634. this.width = value;
  43635. this.height = value;
  43636. },
  43637. enumerable: true,
  43638. configurable: true
  43639. });
  43640. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43641. this._fromIndex = from;
  43642. this._toIndex = to;
  43643. this._loopAnimation = loop;
  43644. this._delay = delay;
  43645. this._animationStarted = true;
  43646. this._direction = from < to ? 1 : -1;
  43647. this.cellIndex = from;
  43648. this._time = 0;
  43649. this._onAnimationEnd = onAnimationEnd;
  43650. };
  43651. Sprite.prototype.stopAnimation = function () {
  43652. this._animationStarted = false;
  43653. };
  43654. Sprite.prototype._animate = function (deltaTime) {
  43655. if (!this._animationStarted)
  43656. return;
  43657. this._time += deltaTime;
  43658. if (this._time > this._delay) {
  43659. this._time = this._time % this._delay;
  43660. this.cellIndex += this._direction;
  43661. if (this.cellIndex > this._toIndex) {
  43662. if (this._loopAnimation) {
  43663. this.cellIndex = this._fromIndex;
  43664. }
  43665. else {
  43666. this.cellIndex = this._toIndex;
  43667. this._animationStarted = false;
  43668. if (this._onAnimationEnd) {
  43669. this._onAnimationEnd();
  43670. }
  43671. if (this.disposeWhenFinishedAnimating) {
  43672. this.dispose();
  43673. }
  43674. }
  43675. }
  43676. }
  43677. };
  43678. Sprite.prototype.dispose = function () {
  43679. for (var i = 0; i < this._manager.sprites.length; i++) {
  43680. if (this._manager.sprites[i] == this) {
  43681. this._manager.sprites.splice(i, 1);
  43682. }
  43683. }
  43684. };
  43685. return Sprite;
  43686. }());
  43687. BABYLON.Sprite = Sprite;
  43688. })(BABYLON || (BABYLON = {}));
  43689. //# sourceMappingURL=babylon.sprite.js.map
  43690. var BABYLON;
  43691. (function (BABYLON) {
  43692. var IntersectionInfo = /** @class */ (function () {
  43693. function IntersectionInfo(bu, bv, distance) {
  43694. this.bu = bu;
  43695. this.bv = bv;
  43696. this.distance = distance;
  43697. this.faceId = 0;
  43698. this.subMeshId = 0;
  43699. }
  43700. return IntersectionInfo;
  43701. }());
  43702. BABYLON.IntersectionInfo = IntersectionInfo;
  43703. var PickingInfo = /** @class */ (function () {
  43704. function PickingInfo() {
  43705. this.hit = false;
  43706. this.distance = 0;
  43707. this.pickedPoint = null;
  43708. this.pickedMesh = null;
  43709. this.bu = 0;
  43710. this.bv = 0;
  43711. this.faceId = -1;
  43712. this.subMeshId = 0;
  43713. this.pickedSprite = null;
  43714. }
  43715. // Methods
  43716. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43717. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43718. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43719. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43720. return null;
  43721. }
  43722. var indices = this.pickedMesh.getIndices();
  43723. if (!indices) {
  43724. return null;
  43725. }
  43726. var result;
  43727. if (useVerticesNormals) {
  43728. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43729. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43730. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43731. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43732. normal0 = normal0.scale(this.bu);
  43733. normal1 = normal1.scale(this.bv);
  43734. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43735. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43736. }
  43737. else {
  43738. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43739. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43740. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43741. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43742. var p1p2 = vertex1.subtract(vertex2);
  43743. var p3p2 = vertex3.subtract(vertex2);
  43744. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43745. }
  43746. if (useWorldCoordinates) {
  43747. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43748. }
  43749. return BABYLON.Vector3.Normalize(result);
  43750. };
  43751. PickingInfo.prototype.getTextureCoordinates = function () {
  43752. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43753. return null;
  43754. }
  43755. var indices = this.pickedMesh.getIndices();
  43756. if (!indices) {
  43757. return null;
  43758. }
  43759. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43760. if (!uvs) {
  43761. return null;
  43762. }
  43763. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43764. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43765. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43766. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43767. uv1 = uv1.scale(this.bu);
  43768. uv2 = uv2.scale(this.bv);
  43769. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43770. };
  43771. return PickingInfo;
  43772. }());
  43773. BABYLON.PickingInfo = PickingInfo;
  43774. })(BABYLON || (BABYLON = {}));
  43775. //# sourceMappingURL=babylon.pickingInfo.js.map
  43776. var BABYLON;
  43777. (function (BABYLON) {
  43778. var Ray = /** @class */ (function () {
  43779. function Ray(origin, direction, length) {
  43780. if (length === void 0) { length = Number.MAX_VALUE; }
  43781. this.origin = origin;
  43782. this.direction = direction;
  43783. this.length = length;
  43784. }
  43785. // Methods
  43786. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43787. var d = 0.0;
  43788. var maxValue = Number.MAX_VALUE;
  43789. var inv;
  43790. var min;
  43791. var max;
  43792. var temp;
  43793. if (Math.abs(this.direction.x) < 0.0000001) {
  43794. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43795. return false;
  43796. }
  43797. }
  43798. else {
  43799. inv = 1.0 / this.direction.x;
  43800. min = (minimum.x - this.origin.x) * inv;
  43801. max = (maximum.x - this.origin.x) * inv;
  43802. if (max === -Infinity) {
  43803. max = Infinity;
  43804. }
  43805. if (min > max) {
  43806. temp = min;
  43807. min = max;
  43808. max = temp;
  43809. }
  43810. d = Math.max(min, d);
  43811. maxValue = Math.min(max, maxValue);
  43812. if (d > maxValue) {
  43813. return false;
  43814. }
  43815. }
  43816. if (Math.abs(this.direction.y) < 0.0000001) {
  43817. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43818. return false;
  43819. }
  43820. }
  43821. else {
  43822. inv = 1.0 / this.direction.y;
  43823. min = (minimum.y - this.origin.y) * inv;
  43824. max = (maximum.y - this.origin.y) * inv;
  43825. if (max === -Infinity) {
  43826. max = Infinity;
  43827. }
  43828. if (min > max) {
  43829. temp = min;
  43830. min = max;
  43831. max = temp;
  43832. }
  43833. d = Math.max(min, d);
  43834. maxValue = Math.min(max, maxValue);
  43835. if (d > maxValue) {
  43836. return false;
  43837. }
  43838. }
  43839. if (Math.abs(this.direction.z) < 0.0000001) {
  43840. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43841. return false;
  43842. }
  43843. }
  43844. else {
  43845. inv = 1.0 / this.direction.z;
  43846. min = (minimum.z - this.origin.z) * inv;
  43847. max = (maximum.z - this.origin.z) * inv;
  43848. if (max === -Infinity) {
  43849. max = Infinity;
  43850. }
  43851. if (min > max) {
  43852. temp = min;
  43853. min = max;
  43854. max = temp;
  43855. }
  43856. d = Math.max(min, d);
  43857. maxValue = Math.min(max, maxValue);
  43858. if (d > maxValue) {
  43859. return false;
  43860. }
  43861. }
  43862. return true;
  43863. };
  43864. Ray.prototype.intersectsBox = function (box) {
  43865. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43866. };
  43867. Ray.prototype.intersectsSphere = function (sphere) {
  43868. var x = sphere.center.x - this.origin.x;
  43869. var y = sphere.center.y - this.origin.y;
  43870. var z = sphere.center.z - this.origin.z;
  43871. var pyth = (x * x) + (y * y) + (z * z);
  43872. var rr = sphere.radius * sphere.radius;
  43873. if (pyth <= rr) {
  43874. return true;
  43875. }
  43876. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43877. if (dot < 0.0) {
  43878. return false;
  43879. }
  43880. var temp = pyth - (dot * dot);
  43881. return temp <= rr;
  43882. };
  43883. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43884. if (!this._edge1) {
  43885. this._edge1 = BABYLON.Vector3.Zero();
  43886. this._edge2 = BABYLON.Vector3.Zero();
  43887. this._pvec = BABYLON.Vector3.Zero();
  43888. this._tvec = BABYLON.Vector3.Zero();
  43889. this._qvec = BABYLON.Vector3.Zero();
  43890. }
  43891. vertex1.subtractToRef(vertex0, this._edge1);
  43892. vertex2.subtractToRef(vertex0, this._edge2);
  43893. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43894. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43895. if (det === 0) {
  43896. return null;
  43897. }
  43898. var invdet = 1 / det;
  43899. this.origin.subtractToRef(vertex0, this._tvec);
  43900. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43901. if (bu < 0 || bu > 1.0) {
  43902. return null;
  43903. }
  43904. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43905. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43906. if (bv < 0 || bu + bv > 1.0) {
  43907. return null;
  43908. }
  43909. //check if the distance is longer than the predefined length.
  43910. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43911. if (distance > this.length) {
  43912. return null;
  43913. }
  43914. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43915. };
  43916. Ray.prototype.intersectsPlane = function (plane) {
  43917. var distance;
  43918. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43919. if (Math.abs(result1) < 9.99999997475243E-07) {
  43920. return null;
  43921. }
  43922. else {
  43923. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43924. distance = (-plane.d - result2) / result1;
  43925. if (distance < 0.0) {
  43926. if (distance < -9.99999997475243E-07) {
  43927. return null;
  43928. }
  43929. else {
  43930. return 0;
  43931. }
  43932. }
  43933. return distance;
  43934. }
  43935. };
  43936. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43937. var tm = BABYLON.Tmp.Matrix[0];
  43938. mesh.getWorldMatrix().invertToRef(tm);
  43939. if (this._tmpRay) {
  43940. Ray.TransformToRef(this, tm, this._tmpRay);
  43941. }
  43942. else {
  43943. this._tmpRay = Ray.Transform(this, tm);
  43944. }
  43945. return mesh.intersects(this._tmpRay, fastCheck);
  43946. };
  43947. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43948. if (results) {
  43949. results.length = 0;
  43950. }
  43951. else {
  43952. results = [];
  43953. }
  43954. for (var i = 0; i < meshes.length; i++) {
  43955. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43956. if (pickInfo.hit) {
  43957. results.push(pickInfo);
  43958. }
  43959. }
  43960. results.sort(this._comparePickingInfo);
  43961. return results;
  43962. };
  43963. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43964. if (pickingInfoA.distance < pickingInfoB.distance) {
  43965. return -1;
  43966. }
  43967. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43968. return 1;
  43969. }
  43970. else {
  43971. return 0;
  43972. }
  43973. };
  43974. /**
  43975. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43976. * @param sega the first point of the segment to test the intersection against
  43977. * @param segb the second point of the segment to test the intersection against
  43978. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43979. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43980. */
  43981. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43982. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43983. var u = segb.subtract(sega);
  43984. var v = rsegb.subtract(this.origin);
  43985. var w = sega.subtract(this.origin);
  43986. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43987. var b = BABYLON.Vector3.Dot(u, v);
  43988. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43989. var d = BABYLON.Vector3.Dot(u, w);
  43990. var e = BABYLON.Vector3.Dot(v, w);
  43991. var D = a * c - b * b; // always >= 0
  43992. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43993. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43994. // compute the line parameters of the two closest points
  43995. if (D < Ray.smallnum) {
  43996. sN = 0.0; // force using point P0 on segment S1
  43997. sD = 1.0; // to prevent possible division by 0.0 later
  43998. tN = e;
  43999. tD = c;
  44000. }
  44001. else {
  44002. sN = (b * e - c * d);
  44003. tN = (a * e - b * d);
  44004. if (sN < 0.0) {
  44005. sN = 0.0;
  44006. tN = e;
  44007. tD = c;
  44008. }
  44009. else if (sN > sD) {
  44010. sN = sD;
  44011. tN = e + b;
  44012. tD = c;
  44013. }
  44014. }
  44015. if (tN < 0.0) {
  44016. tN = 0.0;
  44017. // recompute sc for this edge
  44018. if (-d < 0.0) {
  44019. sN = 0.0;
  44020. }
  44021. else if (-d > a)
  44022. sN = sD;
  44023. else {
  44024. sN = -d;
  44025. sD = a;
  44026. }
  44027. }
  44028. else if (tN > tD) {
  44029. tN = tD;
  44030. // recompute sc for this edge
  44031. if ((-d + b) < 0.0) {
  44032. sN = 0;
  44033. }
  44034. else if ((-d + b) > a) {
  44035. sN = sD;
  44036. }
  44037. else {
  44038. sN = (-d + b);
  44039. sD = a;
  44040. }
  44041. }
  44042. // finally do the division to get sc and tc
  44043. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44044. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44045. // get the difference of the two closest points
  44046. var qtc = v.multiplyByFloats(tc, tc, tc);
  44047. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44048. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44049. if (isIntersected) {
  44050. return qtc.length();
  44051. }
  44052. return -1;
  44053. };
  44054. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44055. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44056. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44057. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44058. this.direction.normalize();
  44059. return this;
  44060. };
  44061. // Statics
  44062. Ray.Zero = function () {
  44063. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44064. };
  44065. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44066. var result = Ray.Zero();
  44067. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44068. };
  44069. /**
  44070. * 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
  44071. * transformed to the given world matrix.
  44072. * @param origin The origin point
  44073. * @param end The end point
  44074. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44075. */
  44076. Ray.CreateNewFromTo = function (origin, end, world) {
  44077. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44078. var direction = end.subtract(origin);
  44079. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44080. direction.normalize();
  44081. return Ray.Transform(new Ray(origin, direction, length), world);
  44082. };
  44083. Ray.Transform = function (ray, matrix) {
  44084. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44085. Ray.TransformToRef(ray, matrix, result);
  44086. return result;
  44087. };
  44088. Ray.TransformToRef = function (ray, matrix, result) {
  44089. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44090. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44091. result.length = ray.length;
  44092. var dir = result.direction;
  44093. var len = dir.length();
  44094. if (!(len === 0 || len === 1)) {
  44095. var num = 1.0 / len;
  44096. dir.x *= num;
  44097. dir.y *= num;
  44098. dir.z *= num;
  44099. result.length *= len;
  44100. }
  44101. };
  44102. Ray.smallnum = 0.00000001;
  44103. Ray.rayl = 10e8;
  44104. return Ray;
  44105. }());
  44106. BABYLON.Ray = Ray;
  44107. })(BABYLON || (BABYLON = {}));
  44108. //# sourceMappingURL=babylon.ray.js.map
  44109. var BABYLON;
  44110. (function (BABYLON) {
  44111. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44112. if (boxMin.x > sphereCenter.x + sphereRadius)
  44113. return false;
  44114. if (sphereCenter.x - sphereRadius > boxMax.x)
  44115. return false;
  44116. if (boxMin.y > sphereCenter.y + sphereRadius)
  44117. return false;
  44118. if (sphereCenter.y - sphereRadius > boxMax.y)
  44119. return false;
  44120. if (boxMin.z > sphereCenter.z + sphereRadius)
  44121. return false;
  44122. if (sphereCenter.z - sphereRadius > boxMax.z)
  44123. return false;
  44124. return true;
  44125. };
  44126. var getLowestRoot = (function () {
  44127. var result = { root: 0, found: false };
  44128. return function (a, b, c, maxR) {
  44129. result.root = 0;
  44130. result.found = false;
  44131. var determinant = b * b - 4.0 * a * c;
  44132. if (determinant < 0)
  44133. return result;
  44134. var sqrtD = Math.sqrt(determinant);
  44135. var r1 = (-b - sqrtD) / (2.0 * a);
  44136. var r2 = (-b + sqrtD) / (2.0 * a);
  44137. if (r1 > r2) {
  44138. var temp = r2;
  44139. r2 = r1;
  44140. r1 = temp;
  44141. }
  44142. if (r1 > 0 && r1 < maxR) {
  44143. result.root = r1;
  44144. result.found = true;
  44145. return result;
  44146. }
  44147. if (r2 > 0 && r2 < maxR) {
  44148. result.root = r2;
  44149. result.found = true;
  44150. return result;
  44151. }
  44152. return result;
  44153. };
  44154. })();
  44155. var Collider = /** @class */ (function () {
  44156. function Collider() {
  44157. this.radius = BABYLON.Vector3.One();
  44158. this.retry = 0;
  44159. this.basePointWorld = BABYLON.Vector3.Zero();
  44160. this.velocityWorld = BABYLON.Vector3.Zero();
  44161. this.normalizedVelocity = BABYLON.Vector3.Zero();
  44162. this._collisionPoint = BABYLON.Vector3.Zero();
  44163. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44164. this._tempVector = BABYLON.Vector3.Zero();
  44165. this._tempVector2 = BABYLON.Vector3.Zero();
  44166. this._tempVector3 = BABYLON.Vector3.Zero();
  44167. this._tempVector4 = BABYLON.Vector3.Zero();
  44168. this._edge = BABYLON.Vector3.Zero();
  44169. this._baseToVertex = BABYLON.Vector3.Zero();
  44170. this._destinationPoint = BABYLON.Vector3.Zero();
  44171. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44172. this._displacementVector = BABYLON.Vector3.Zero();
  44173. this._collisionMask = -1;
  44174. }
  44175. Object.defineProperty(Collider.prototype, "collisionMask", {
  44176. get: function () {
  44177. return this._collisionMask;
  44178. },
  44179. set: function (mask) {
  44180. this._collisionMask = !isNaN(mask) ? mask : -1;
  44181. },
  44182. enumerable: true,
  44183. configurable: true
  44184. });
  44185. // Methods
  44186. Collider.prototype._initialize = function (source, dir, e) {
  44187. this.velocity = dir;
  44188. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  44189. this.basePoint = source;
  44190. source.multiplyToRef(this.radius, this.basePointWorld);
  44191. dir.multiplyToRef(this.radius, this.velocityWorld);
  44192. this.velocityWorldLength = this.velocityWorld.length();
  44193. this.epsilon = e;
  44194. this.collisionFound = false;
  44195. };
  44196. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44197. pa.subtractToRef(point, this._tempVector);
  44198. pb.subtractToRef(point, this._tempVector2);
  44199. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44200. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44201. if (d < 0)
  44202. return false;
  44203. pc.subtractToRef(point, this._tempVector3);
  44204. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44205. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44206. if (d < 0)
  44207. return false;
  44208. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44209. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44210. return d >= 0;
  44211. };
  44212. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44213. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  44214. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  44215. if (distance > this.velocityWorldLength + max + sphereRadius) {
  44216. return false;
  44217. }
  44218. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  44219. return false;
  44220. return true;
  44221. };
  44222. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44223. var t0;
  44224. var embeddedInPlane = false;
  44225. //defensive programming, actually not needed.
  44226. if (!trianglePlaneArray) {
  44227. trianglePlaneArray = [];
  44228. }
  44229. if (!trianglePlaneArray[faceIndex]) {
  44230. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44231. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44232. }
  44233. var trianglePlane = trianglePlaneArray[faceIndex];
  44234. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  44235. return;
  44236. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  44237. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  44238. if (normalDotVelocity == 0) {
  44239. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44240. return;
  44241. embeddedInPlane = true;
  44242. t0 = 0;
  44243. }
  44244. else {
  44245. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44246. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44247. if (t0 > t1) {
  44248. var temp = t1;
  44249. t1 = t0;
  44250. t0 = temp;
  44251. }
  44252. if (t0 > 1.0 || t1 < 0.0)
  44253. return;
  44254. if (t0 < 0)
  44255. t0 = 0;
  44256. if (t0 > 1.0)
  44257. t0 = 1.0;
  44258. }
  44259. this._collisionPoint.copyFromFloats(0, 0, 0);
  44260. var found = false;
  44261. var t = 1.0;
  44262. if (!embeddedInPlane) {
  44263. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44264. this.velocity.scaleToRef(t0, this._tempVector);
  44265. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44266. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44267. found = true;
  44268. t = t0;
  44269. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44270. }
  44271. }
  44272. if (!found) {
  44273. var velocitySquaredLength = this.velocity.lengthSquared();
  44274. var a = velocitySquaredLength;
  44275. this.basePoint.subtractToRef(p1, this._tempVector);
  44276. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44277. var c = this._tempVector.lengthSquared() - 1.0;
  44278. var lowestRoot = getLowestRoot(a, b, c, t);
  44279. if (lowestRoot.found) {
  44280. t = lowestRoot.root;
  44281. found = true;
  44282. this._collisionPoint.copyFrom(p1);
  44283. }
  44284. this.basePoint.subtractToRef(p2, this._tempVector);
  44285. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44286. c = this._tempVector.lengthSquared() - 1.0;
  44287. lowestRoot = getLowestRoot(a, b, c, t);
  44288. if (lowestRoot.found) {
  44289. t = lowestRoot.root;
  44290. found = true;
  44291. this._collisionPoint.copyFrom(p2);
  44292. }
  44293. this.basePoint.subtractToRef(p3, this._tempVector);
  44294. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44295. c = this._tempVector.lengthSquared() - 1.0;
  44296. lowestRoot = getLowestRoot(a, b, c, t);
  44297. if (lowestRoot.found) {
  44298. t = lowestRoot.root;
  44299. found = true;
  44300. this._collisionPoint.copyFrom(p3);
  44301. }
  44302. p2.subtractToRef(p1, this._edge);
  44303. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44304. var edgeSquaredLength = this._edge.lengthSquared();
  44305. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44306. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44307. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44308. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44309. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44310. lowestRoot = getLowestRoot(a, b, c, t);
  44311. if (lowestRoot.found) {
  44312. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44313. if (f >= 0.0 && f <= 1.0) {
  44314. t = lowestRoot.root;
  44315. found = true;
  44316. this._edge.scaleInPlace(f);
  44317. p1.addToRef(this._edge, this._collisionPoint);
  44318. }
  44319. }
  44320. p3.subtractToRef(p2, this._edge);
  44321. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44322. edgeSquaredLength = this._edge.lengthSquared();
  44323. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44324. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44325. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44326. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44327. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44328. lowestRoot = getLowestRoot(a, b, c, t);
  44329. if (lowestRoot.found) {
  44330. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44331. if (f >= 0.0 && f <= 1.0) {
  44332. t = lowestRoot.root;
  44333. found = true;
  44334. this._edge.scaleInPlace(f);
  44335. p2.addToRef(this._edge, this._collisionPoint);
  44336. }
  44337. }
  44338. p1.subtractToRef(p3, this._edge);
  44339. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44340. edgeSquaredLength = this._edge.lengthSquared();
  44341. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44342. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44343. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44344. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44345. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44346. lowestRoot = getLowestRoot(a, b, c, t);
  44347. if (lowestRoot.found) {
  44348. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44349. if (f >= 0.0 && f <= 1.0) {
  44350. t = lowestRoot.root;
  44351. found = true;
  44352. this._edge.scaleInPlace(f);
  44353. p3.addToRef(this._edge, this._collisionPoint);
  44354. }
  44355. }
  44356. }
  44357. if (found) {
  44358. var distToCollision = t * this.velocity.length();
  44359. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44360. if (!this.intersectionPoint) {
  44361. this.intersectionPoint = this._collisionPoint.clone();
  44362. }
  44363. else {
  44364. this.intersectionPoint.copyFrom(this._collisionPoint);
  44365. }
  44366. this.nearestDistance = distToCollision;
  44367. this.collisionFound = true;
  44368. }
  44369. }
  44370. };
  44371. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44372. for (var i = indexStart; i < indexEnd; i += 3) {
  44373. var p1 = pts[indices[i] - decal];
  44374. var p2 = pts[indices[i + 1] - decal];
  44375. var p3 = pts[indices[i + 2] - decal];
  44376. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44377. }
  44378. };
  44379. Collider.prototype._getResponse = function (pos, vel) {
  44380. pos.addToRef(vel, this._destinationPoint);
  44381. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44382. this.basePoint.addToRef(vel, pos);
  44383. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44384. this._slidePlaneNormal.normalize();
  44385. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44386. pos.addInPlace(this._displacementVector);
  44387. this.intersectionPoint.addInPlace(this._displacementVector);
  44388. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44389. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44390. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44391. };
  44392. return Collider;
  44393. }());
  44394. BABYLON.Collider = Collider;
  44395. })(BABYLON || (BABYLON = {}));
  44396. //# sourceMappingURL=babylon.collider.js.map
  44397. var BABYLON;
  44398. (function (BABYLON) {
  44399. //WebWorker code will be inserted to this variable.
  44400. BABYLON.CollisionWorker = "";
  44401. var WorkerTaskType;
  44402. (function (WorkerTaskType) {
  44403. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44404. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44405. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44406. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44407. var WorkerReplyType;
  44408. (function (WorkerReplyType) {
  44409. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44410. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44411. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44412. var CollisionCoordinatorWorker = /** @class */ (function () {
  44413. function CollisionCoordinatorWorker() {
  44414. var _this = this;
  44415. this._scaledPosition = BABYLON.Vector3.Zero();
  44416. this._scaledVelocity = BABYLON.Vector3.Zero();
  44417. this.onMeshUpdated = function (transformNode) {
  44418. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44419. };
  44420. this.onGeometryUpdated = function (geometry) {
  44421. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44422. };
  44423. this._afterRender = function () {
  44424. if (!_this._init)
  44425. return;
  44426. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44427. return;
  44428. }
  44429. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44430. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44431. if (_this._runningUpdated > 4) {
  44432. return;
  44433. }
  44434. ++_this._runningUpdated;
  44435. var payload = {
  44436. updatedMeshes: _this._addUpdateMeshesList,
  44437. updatedGeometries: _this._addUpdateGeometriesList,
  44438. removedGeometries: _this._toRemoveGeometryArray,
  44439. removedMeshes: _this._toRemoveMeshesArray
  44440. };
  44441. var message = {
  44442. payload: payload,
  44443. taskType: WorkerTaskType.UPDATE
  44444. };
  44445. var serializable = [];
  44446. for (var id in payload.updatedGeometries) {
  44447. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44448. //prepare transferables
  44449. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44450. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44451. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44452. }
  44453. }
  44454. _this._worker.postMessage(message, serializable);
  44455. _this._addUpdateMeshesList = {};
  44456. _this._addUpdateGeometriesList = {};
  44457. _this._toRemoveGeometryArray = [];
  44458. _this._toRemoveMeshesArray = [];
  44459. };
  44460. this._onMessageFromWorker = function (e) {
  44461. var returnData = e.data;
  44462. if (returnData.error != WorkerReplyType.SUCCESS) {
  44463. //TODO what errors can be returned from the worker?
  44464. BABYLON.Tools.Warn("error returned from worker!");
  44465. return;
  44466. }
  44467. switch (returnData.taskType) {
  44468. case WorkerTaskType.INIT:
  44469. _this._init = true;
  44470. //Update the worked with ALL of the scene's current state
  44471. _this._scene.meshes.forEach(function (mesh) {
  44472. _this.onMeshAdded(mesh);
  44473. });
  44474. _this._scene.getGeometries().forEach(function (geometry) {
  44475. _this.onGeometryAdded(geometry);
  44476. });
  44477. break;
  44478. case WorkerTaskType.UPDATE:
  44479. _this._runningUpdated--;
  44480. break;
  44481. case WorkerTaskType.COLLIDE:
  44482. var returnPayload = returnData.payload;
  44483. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44484. return;
  44485. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44486. if (callback) {
  44487. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44488. if (mesh) {
  44489. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44490. }
  44491. }
  44492. //cleanup
  44493. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44494. break;
  44495. }
  44496. };
  44497. this._collisionsCallbackArray = [];
  44498. this._init = false;
  44499. this._runningUpdated = 0;
  44500. this._addUpdateMeshesList = {};
  44501. this._addUpdateGeometriesList = {};
  44502. this._toRemoveGeometryArray = [];
  44503. this._toRemoveMeshesArray = [];
  44504. }
  44505. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44506. if (!this._init)
  44507. return;
  44508. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44509. return;
  44510. position.divideToRef(collider.radius, this._scaledPosition);
  44511. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44512. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44513. var payload = {
  44514. collider: {
  44515. position: this._scaledPosition.asArray(),
  44516. velocity: this._scaledVelocity.asArray(),
  44517. radius: collider.radius.asArray()
  44518. },
  44519. collisionId: collisionIndex,
  44520. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44521. maximumRetry: maximumRetry
  44522. };
  44523. var message = {
  44524. payload: payload,
  44525. taskType: WorkerTaskType.COLLIDE
  44526. };
  44527. this._worker.postMessage(message);
  44528. };
  44529. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44530. this._scene = scene;
  44531. this._scene.registerAfterRender(this._afterRender);
  44532. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44533. this._worker = new Worker(workerUrl);
  44534. this._worker.onmessage = this._onMessageFromWorker;
  44535. var message = {
  44536. payload: {},
  44537. taskType: WorkerTaskType.INIT
  44538. };
  44539. this._worker.postMessage(message);
  44540. };
  44541. CollisionCoordinatorWorker.prototype.destroy = function () {
  44542. this._scene.unregisterAfterRender(this._afterRender);
  44543. this._worker.terminate();
  44544. };
  44545. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44546. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44547. this.onMeshUpdated(mesh);
  44548. };
  44549. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44550. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44551. };
  44552. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44553. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44554. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44555. this.onGeometryUpdated(geometry);
  44556. };
  44557. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44558. this._toRemoveGeometryArray.push(geometry.id);
  44559. };
  44560. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44561. var submeshes = [];
  44562. if (mesh.subMeshes) {
  44563. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44564. var boundingInfo = sm.getBoundingInfo();
  44565. return {
  44566. position: idx,
  44567. verticesStart: sm.verticesStart,
  44568. verticesCount: sm.verticesCount,
  44569. indexStart: sm.indexStart,
  44570. indexCount: sm.indexCount,
  44571. hasMaterial: !!sm.getMaterial(),
  44572. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44573. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44574. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44575. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44576. };
  44577. });
  44578. }
  44579. var geometryId = null;
  44580. if (mesh instanceof BABYLON.Mesh) {
  44581. var geometry = mesh.geometry;
  44582. geometryId = geometry ? geometry.id : null;
  44583. }
  44584. else if (mesh instanceof BABYLON.InstancedMesh) {
  44585. var geometry = mesh.sourceMesh.geometry;
  44586. geometryId = geometry ? geometry.id : null;
  44587. }
  44588. var boundingInfo = mesh.getBoundingInfo();
  44589. return {
  44590. uniqueId: mesh.uniqueId,
  44591. id: mesh.id,
  44592. name: mesh.name,
  44593. geometryId: geometryId,
  44594. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44595. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44596. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44597. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44598. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44599. subMeshes: submeshes,
  44600. checkCollisions: mesh.checkCollisions
  44601. };
  44602. };
  44603. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44604. return {
  44605. id: geometry.id,
  44606. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44607. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44608. indices: new Uint32Array(geometry.getIndices() || []),
  44609. };
  44610. };
  44611. return CollisionCoordinatorWorker;
  44612. }());
  44613. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44614. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44615. function CollisionCoordinatorLegacy() {
  44616. this._scaledPosition = BABYLON.Vector3.Zero();
  44617. this._scaledVelocity = BABYLON.Vector3.Zero();
  44618. this._finalPosition = BABYLON.Vector3.Zero();
  44619. }
  44620. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44621. position.divideToRef(collider.radius, this._scaledPosition);
  44622. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44623. collider.collidedMesh = null;
  44624. collider.retry = 0;
  44625. collider.initialVelocity = this._scaledVelocity;
  44626. collider.initialPosition = this._scaledPosition;
  44627. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44628. this._finalPosition.multiplyInPlace(collider.radius);
  44629. //run the callback
  44630. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44631. };
  44632. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44633. this._scene = scene;
  44634. };
  44635. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44636. //Legacy need no destruction method.
  44637. };
  44638. //No update in legacy mode
  44639. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44640. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44641. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44642. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44643. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44644. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44645. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44646. if (excludedMesh === void 0) { excludedMesh = null; }
  44647. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44648. if (collider.retry >= maximumRetry) {
  44649. finalPosition.copyFrom(position);
  44650. return;
  44651. }
  44652. // Check if this is a mesh else camera or -1
  44653. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44654. collider._initialize(position, velocity, closeDistance);
  44655. // Check all meshes
  44656. for (var index = 0; index < this._scene.meshes.length; index++) {
  44657. var mesh = this._scene.meshes[index];
  44658. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44659. mesh._checkCollision(collider);
  44660. }
  44661. }
  44662. if (!collider.collisionFound) {
  44663. position.addToRef(velocity, finalPosition);
  44664. return;
  44665. }
  44666. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44667. collider._getResponse(position, velocity);
  44668. }
  44669. if (velocity.length() <= closeDistance) {
  44670. finalPosition.copyFrom(position);
  44671. return;
  44672. }
  44673. collider.retry++;
  44674. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44675. };
  44676. return CollisionCoordinatorLegacy;
  44677. }());
  44678. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44679. })(BABYLON || (BABYLON = {}));
  44680. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44681. var BABYLON;
  44682. (function (BABYLON) {
  44683. var Particle = /** @class */ (function () {
  44684. function Particle(particleSystem) {
  44685. this.particleSystem = particleSystem;
  44686. this.position = BABYLON.Vector3.Zero();
  44687. this.direction = BABYLON.Vector3.Zero();
  44688. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44689. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44690. this.lifeTime = 1.0;
  44691. this.age = 0;
  44692. this.size = 0;
  44693. this.angle = 0;
  44694. this.angularSpeed = 0;
  44695. this._currentFrameCounter = 0;
  44696. this.cellIndex = 0;
  44697. if (!this.particleSystem.isAnimationSheetEnabled) {
  44698. return;
  44699. }
  44700. this.cellIndex = this.particleSystem.startSpriteCellID;
  44701. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44702. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44703. }
  44704. else {
  44705. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44706. }
  44707. }
  44708. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44709. // (ageOffset / scaledUpdateSpeed) / available cells
  44710. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44711. this._currentFrameCounter += scaledUpdateSpeed;
  44712. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44713. this._currentFrameCounter = 0;
  44714. this.cellIndex++;
  44715. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44716. this.cellIndex = this.particleSystem.endSpriteCellID;
  44717. }
  44718. }
  44719. };
  44720. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44721. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44722. this.cellIndex++;
  44723. this._currentFrameCounter = 0;
  44724. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44725. if (this.particleSystem.spriteCellLoop) {
  44726. this.cellIndex = this.particleSystem.startSpriteCellID;
  44727. }
  44728. else {
  44729. this.cellIndex = this.particleSystem.endSpriteCellID;
  44730. }
  44731. }
  44732. }
  44733. else {
  44734. this._currentFrameCounter++;
  44735. }
  44736. };
  44737. Particle.prototype.copyTo = function (other) {
  44738. other.position.copyFrom(this.position);
  44739. other.direction.copyFrom(this.direction);
  44740. other.color.copyFrom(this.color);
  44741. other.colorStep.copyFrom(this.colorStep);
  44742. other.lifeTime = this.lifeTime;
  44743. other.age = this.age;
  44744. other.size = this.size;
  44745. other.angle = this.angle;
  44746. other.angularSpeed = this.angularSpeed;
  44747. other.particleSystem = this.particleSystem;
  44748. other.cellIndex = this.cellIndex;
  44749. };
  44750. return Particle;
  44751. }());
  44752. BABYLON.Particle = Particle;
  44753. })(BABYLON || (BABYLON = {}));
  44754. //# sourceMappingURL=babylon.particle.js.map
  44755. var BABYLON;
  44756. (function (BABYLON) {
  44757. var randomNumber = function (min, max) {
  44758. if (min === max) {
  44759. return (min);
  44760. }
  44761. var random = Math.random();
  44762. return ((random * (max - min)) + min);
  44763. };
  44764. var ParticleSystem = /** @class */ (function () {
  44765. // end of sheet animation
  44766. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44767. if (customEffect === void 0) { customEffect = null; }
  44768. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44769. if (epsilon === void 0) { epsilon = 0.01; }
  44770. var _this = this;
  44771. this.name = name;
  44772. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44773. // Members
  44774. this.animations = [];
  44775. this.renderingGroupId = 0;
  44776. this.emitter = null;
  44777. this.emitRate = 10;
  44778. this.manualEmitCount = -1;
  44779. this.updateSpeed = 0.01;
  44780. this.targetStopDuration = 0;
  44781. this.disposeOnStop = false;
  44782. this.minEmitPower = 1;
  44783. this.maxEmitPower = 1;
  44784. this.minLifeTime = 1;
  44785. this.maxLifeTime = 1;
  44786. this.minSize = 1;
  44787. this.maxSize = 1;
  44788. this.minAngularSpeed = 0;
  44789. this.maxAngularSpeed = 0;
  44790. this.layerMask = 0x0FFFFFFF;
  44791. this.customShader = null;
  44792. this.preventAutoStart = false;
  44793. /**
  44794. * An event triggered when the system is disposed.
  44795. * @type {BABYLON.Observable}
  44796. */
  44797. this.onDisposeObservable = new BABYLON.Observable();
  44798. this.onAnimationEnd = null;
  44799. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44800. this.forceDepthWrite = false;
  44801. this.gravity = BABYLON.Vector3.Zero();
  44802. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44803. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44804. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44805. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44806. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44807. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44808. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44809. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44810. this.particles = new Array();
  44811. this._stockParticles = new Array();
  44812. this._newPartsExcess = 0;
  44813. this._vertexBuffers = {};
  44814. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44815. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44816. this._scaledDirection = BABYLON.Vector3.Zero();
  44817. this._scaledGravity = BABYLON.Vector3.Zero();
  44818. this._currentRenderId = -1;
  44819. this._started = false;
  44820. this._stopped = false;
  44821. this._actualFrame = 0;
  44822. // sheet animation
  44823. this.startSpriteCellID = 0;
  44824. this.endSpriteCellID = 0;
  44825. this.spriteCellLoop = true;
  44826. this.spriteCellChangeSpeed = 0;
  44827. this.spriteCellWidth = 0;
  44828. this.spriteCellHeight = 0;
  44829. this._vertexBufferSize = 11;
  44830. this.appendParticleVertexes = null;
  44831. this.id = name;
  44832. this._capacity = capacity;
  44833. this._epsilon = epsilon;
  44834. if (_isAnimationSheetEnabled) {
  44835. this._vertexBufferSize = 12;
  44836. }
  44837. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44838. this._customEffect = customEffect;
  44839. scene.particleSystems.push(this);
  44840. this._createIndexBuffer();
  44841. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44842. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44843. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44844. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44845. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44846. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44847. if (this._isAnimationSheetEnabled) {
  44848. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44849. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44850. }
  44851. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44852. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44853. this._vertexBuffers["options"] = options;
  44854. // Default behaviors
  44855. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44856. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44857. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44858. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44859. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44860. };
  44861. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44862. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44863. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44864. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44866. };
  44867. this.updateFunction = function (particles) {
  44868. for (var index = 0; index < particles.length; index++) {
  44869. var particle = particles[index];
  44870. particle.age += _this._scaledUpdateSpeed;
  44871. if (particle.age >= particle.lifeTime) {
  44872. _this.recycleParticle(particle);
  44873. index--;
  44874. continue;
  44875. }
  44876. else {
  44877. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44878. particle.color.addInPlace(_this._scaledColorStep);
  44879. if (particle.color.a < 0)
  44880. particle.color.a = 0;
  44881. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44882. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44883. particle.position.addInPlace(_this._scaledDirection);
  44884. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44885. particle.direction.addInPlace(_this._scaledGravity);
  44886. if (_this._isAnimationSheetEnabled) {
  44887. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44888. }
  44889. }
  44890. }
  44891. };
  44892. }
  44893. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44894. set: function (callback) {
  44895. if (this._onDisposeObserver) {
  44896. this.onDisposeObservable.remove(this._onDisposeObserver);
  44897. }
  44898. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44899. },
  44900. enumerable: true,
  44901. configurable: true
  44902. });
  44903. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44904. get: function () {
  44905. return this._isAnimationSheetEnabled;
  44906. },
  44907. enumerable: true,
  44908. configurable: true
  44909. });
  44910. ParticleSystem.prototype._createIndexBuffer = function () {
  44911. var indices = [];
  44912. var index = 0;
  44913. for (var count = 0; count < this._capacity; count++) {
  44914. indices.push(index);
  44915. indices.push(index + 1);
  44916. indices.push(index + 2);
  44917. indices.push(index);
  44918. indices.push(index + 2);
  44919. indices.push(index + 3);
  44920. index += 4;
  44921. }
  44922. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44923. };
  44924. ParticleSystem.prototype.recycleParticle = function (particle) {
  44925. var lastParticle = this.particles.pop();
  44926. if (lastParticle !== particle) {
  44927. lastParticle.copyTo(particle);
  44928. this._stockParticles.push(lastParticle);
  44929. }
  44930. };
  44931. ParticleSystem.prototype.getCapacity = function () {
  44932. return this._capacity;
  44933. };
  44934. ParticleSystem.prototype.isAlive = function () {
  44935. return this._alive;
  44936. };
  44937. ParticleSystem.prototype.isStarted = function () {
  44938. return this._started;
  44939. };
  44940. ParticleSystem.prototype.start = function () {
  44941. this._started = true;
  44942. this._stopped = false;
  44943. this._actualFrame = 0;
  44944. };
  44945. ParticleSystem.prototype.stop = function () {
  44946. this._stopped = true;
  44947. };
  44948. // animation sheet
  44949. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44950. var offset = index * this._vertexBufferSize;
  44951. this._vertexData[offset] = particle.position.x;
  44952. this._vertexData[offset + 1] = particle.position.y;
  44953. this._vertexData[offset + 2] = particle.position.z;
  44954. this._vertexData[offset + 3] = particle.color.r;
  44955. this._vertexData[offset + 4] = particle.color.g;
  44956. this._vertexData[offset + 5] = particle.color.b;
  44957. this._vertexData[offset + 6] = particle.color.a;
  44958. this._vertexData[offset + 7] = particle.angle;
  44959. this._vertexData[offset + 8] = particle.size;
  44960. this._vertexData[offset + 9] = offsetX;
  44961. this._vertexData[offset + 10] = offsetY;
  44962. };
  44963. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44964. if (offsetX === 0)
  44965. offsetX = this._epsilon;
  44966. else if (offsetX === 1)
  44967. offsetX = 1 - this._epsilon;
  44968. if (offsetY === 0)
  44969. offsetY = this._epsilon;
  44970. else if (offsetY === 1)
  44971. offsetY = 1 - this._epsilon;
  44972. var offset = index * this._vertexBufferSize;
  44973. this._vertexData[offset] = particle.position.x;
  44974. this._vertexData[offset + 1] = particle.position.y;
  44975. this._vertexData[offset + 2] = particle.position.z;
  44976. this._vertexData[offset + 3] = particle.color.r;
  44977. this._vertexData[offset + 4] = particle.color.g;
  44978. this._vertexData[offset + 5] = particle.color.b;
  44979. this._vertexData[offset + 6] = particle.color.a;
  44980. this._vertexData[offset + 7] = particle.angle;
  44981. this._vertexData[offset + 8] = particle.size;
  44982. this._vertexData[offset + 9] = offsetX;
  44983. this._vertexData[offset + 10] = offsetY;
  44984. this._vertexData[offset + 11] = particle.cellIndex;
  44985. };
  44986. ParticleSystem.prototype._update = function (newParticles) {
  44987. // Update current
  44988. this._alive = this.particles.length > 0;
  44989. this.updateFunction(this.particles);
  44990. // Add new ones
  44991. var worldMatrix;
  44992. if (this.emitter.position) {
  44993. var emitterMesh = this.emitter;
  44994. worldMatrix = emitterMesh.getWorldMatrix();
  44995. }
  44996. else {
  44997. var emitterPosition = this.emitter;
  44998. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44999. }
  45000. var particle;
  45001. for (var index = 0; index < newParticles; index++) {
  45002. if (this.particles.length === this._capacity) {
  45003. break;
  45004. }
  45005. if (this._stockParticles.length !== 0) {
  45006. particle = this._stockParticles.pop();
  45007. particle.age = 0;
  45008. particle.cellIndex = this.startSpriteCellID;
  45009. }
  45010. else {
  45011. particle = new BABYLON.Particle(this);
  45012. }
  45013. this.particles.push(particle);
  45014. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45015. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45016. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45017. particle.size = randomNumber(this.minSize, this.maxSize);
  45018. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45019. this.startPositionFunction(worldMatrix, particle.position, particle);
  45020. var step = randomNumber(0, 1.0);
  45021. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45022. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45023. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45024. }
  45025. };
  45026. ParticleSystem.prototype._getEffect = function () {
  45027. if (this._customEffect) {
  45028. return this._customEffect;
  45029. }
  45030. ;
  45031. var defines = [];
  45032. if (this._scene.clipPlane) {
  45033. defines.push("#define CLIPPLANE");
  45034. }
  45035. if (this._isAnimationSheetEnabled) {
  45036. defines.push("#define ANIMATESHEET");
  45037. }
  45038. // Effect
  45039. var join = defines.join("\n");
  45040. if (this._cachedDefines !== join) {
  45041. this._cachedDefines = join;
  45042. var attributesNamesOrOptions;
  45043. var effectCreationOption;
  45044. if (this._isAnimationSheetEnabled) {
  45045. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45046. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45047. }
  45048. else {
  45049. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45050. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45051. }
  45052. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45053. }
  45054. return this._effect;
  45055. };
  45056. ParticleSystem.prototype.animate = function () {
  45057. if (!this._started)
  45058. return;
  45059. var effect = this._getEffect();
  45060. // Check
  45061. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45062. return;
  45063. if (this._currentRenderId === this._scene.getRenderId()) {
  45064. return;
  45065. }
  45066. this._currentRenderId = this._scene.getRenderId();
  45067. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45068. // determine the number of particles we need to create
  45069. var newParticles;
  45070. if (this.manualEmitCount > -1) {
  45071. newParticles = this.manualEmitCount;
  45072. this._newPartsExcess = 0;
  45073. this.manualEmitCount = 0;
  45074. }
  45075. else {
  45076. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45077. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45078. }
  45079. if (this._newPartsExcess > 1.0) {
  45080. newParticles += this._newPartsExcess >> 0;
  45081. this._newPartsExcess -= this._newPartsExcess >> 0;
  45082. }
  45083. this._alive = false;
  45084. if (!this._stopped) {
  45085. this._actualFrame += this._scaledUpdateSpeed;
  45086. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45087. this.stop();
  45088. }
  45089. else {
  45090. newParticles = 0;
  45091. }
  45092. this._update(newParticles);
  45093. // Stopped?
  45094. if (this._stopped) {
  45095. if (!this._alive) {
  45096. this._started = false;
  45097. if (this.onAnimationEnd) {
  45098. this.onAnimationEnd();
  45099. }
  45100. if (this.disposeOnStop) {
  45101. this._scene._toBeDisposed.push(this);
  45102. }
  45103. }
  45104. }
  45105. // Animation sheet
  45106. if (this._isAnimationSheetEnabled) {
  45107. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45108. }
  45109. else {
  45110. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45111. }
  45112. // Update VBO
  45113. var offset = 0;
  45114. for (var index = 0; index < this.particles.length; index++) {
  45115. var particle = this.particles[index];
  45116. this.appendParticleVertexes(offset, particle);
  45117. offset += 4;
  45118. }
  45119. if (this._vertexBuffer) {
  45120. this._vertexBuffer.update(this._vertexData);
  45121. }
  45122. };
  45123. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45124. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45125. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45126. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45127. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45128. };
  45129. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45130. this._appendParticleVertex(offset++, particle, 0, 0);
  45131. this._appendParticleVertex(offset++, particle, 1, 0);
  45132. this._appendParticleVertex(offset++, particle, 1, 1);
  45133. this._appendParticleVertex(offset++, particle, 0, 1);
  45134. };
  45135. ParticleSystem.prototype.rebuild = function () {
  45136. this._createIndexBuffer();
  45137. if (this._vertexBuffer) {
  45138. this._vertexBuffer._rebuild();
  45139. }
  45140. };
  45141. ParticleSystem.prototype.render = function () {
  45142. var effect = this._getEffect();
  45143. // Check
  45144. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45145. return 0;
  45146. var engine = this._scene.getEngine();
  45147. // Render
  45148. engine.enableEffect(effect);
  45149. engine.setState(false);
  45150. var viewMatrix = this._scene.getViewMatrix();
  45151. effect.setTexture("diffuseSampler", this.particleTexture);
  45152. effect.setMatrix("view", viewMatrix);
  45153. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45154. if (this._isAnimationSheetEnabled) {
  45155. var baseSize = this.particleTexture.getBaseSize();
  45156. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45157. }
  45158. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45159. if (this._scene.clipPlane) {
  45160. var clipPlane = this._scene.clipPlane;
  45161. var invView = viewMatrix.clone();
  45162. invView.invert();
  45163. effect.setMatrix("invView", invView);
  45164. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45165. }
  45166. // VBOs
  45167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45168. // Draw order
  45169. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45170. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45171. }
  45172. else {
  45173. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45174. }
  45175. if (this.forceDepthWrite) {
  45176. engine.setDepthWrite(true);
  45177. }
  45178. engine.draw(true, 0, this.particles.length * 6);
  45179. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45180. return this.particles.length;
  45181. };
  45182. ParticleSystem.prototype.dispose = function () {
  45183. if (this._vertexBuffer) {
  45184. this._vertexBuffer.dispose();
  45185. this._vertexBuffer = null;
  45186. }
  45187. if (this._indexBuffer) {
  45188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45189. this._indexBuffer = null;
  45190. }
  45191. if (this.particleTexture) {
  45192. this.particleTexture.dispose();
  45193. this.particleTexture = null;
  45194. }
  45195. // Remove from scene
  45196. var index = this._scene.particleSystems.indexOf(this);
  45197. if (index > -1) {
  45198. this._scene.particleSystems.splice(index, 1);
  45199. }
  45200. // Callback
  45201. this.onDisposeObservable.notifyObservers(this);
  45202. this.onDisposeObservable.clear();
  45203. };
  45204. // Clone
  45205. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45206. var custom = null;
  45207. var program = null;
  45208. if (this.customShader != null) {
  45209. program = this.customShader;
  45210. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45211. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45212. }
  45213. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45214. result.customShader = program;
  45215. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45216. if (newEmitter === undefined) {
  45217. newEmitter = this.emitter;
  45218. }
  45219. result.emitter = newEmitter;
  45220. if (this.particleTexture) {
  45221. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45222. }
  45223. if (!this.preventAutoStart) {
  45224. result.start();
  45225. }
  45226. return result;
  45227. };
  45228. ParticleSystem.prototype.serialize = function () {
  45229. var serializationObject = {};
  45230. serializationObject.name = this.name;
  45231. serializationObject.id = this.id;
  45232. // Emitter
  45233. if (this.emitter.position) {
  45234. var emitterMesh = this.emitter;
  45235. serializationObject.emitterId = emitterMesh.id;
  45236. }
  45237. else {
  45238. var emitterPosition = this.emitter;
  45239. serializationObject.emitter = emitterPosition.asArray();
  45240. }
  45241. serializationObject.capacity = this.getCapacity();
  45242. if (this.particleTexture) {
  45243. serializationObject.textureName = this.particleTexture.name;
  45244. }
  45245. // Animations
  45246. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45247. // Particle system
  45248. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45249. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45250. serializationObject.minSize = this.minSize;
  45251. serializationObject.maxSize = this.maxSize;
  45252. serializationObject.minEmitPower = this.minEmitPower;
  45253. serializationObject.maxEmitPower = this.maxEmitPower;
  45254. serializationObject.minLifeTime = this.minLifeTime;
  45255. serializationObject.maxLifeTime = this.maxLifeTime;
  45256. serializationObject.emitRate = this.emitRate;
  45257. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45258. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45259. serializationObject.gravity = this.gravity.asArray();
  45260. serializationObject.direction1 = this.direction1.asArray();
  45261. serializationObject.direction2 = this.direction2.asArray();
  45262. serializationObject.color1 = this.color1.asArray();
  45263. serializationObject.color2 = this.color2.asArray();
  45264. serializationObject.colorDead = this.colorDead.asArray();
  45265. serializationObject.updateSpeed = this.updateSpeed;
  45266. serializationObject.targetStopDuration = this.targetStopDuration;
  45267. serializationObject.textureMask = this.textureMask.asArray();
  45268. serializationObject.blendMode = this.blendMode;
  45269. serializationObject.customShader = this.customShader;
  45270. serializationObject.preventAutoStart = this.preventAutoStart;
  45271. return serializationObject;
  45272. };
  45273. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45274. var name = parsedParticleSystem.name;
  45275. var custom = null;
  45276. var program = null;
  45277. if (parsedParticleSystem.customShader) {
  45278. program = parsedParticleSystem.customShader;
  45279. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45280. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45281. }
  45282. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  45283. particleSystem.customShader = program;
  45284. if (parsedParticleSystem.id) {
  45285. particleSystem.id = parsedParticleSystem.id;
  45286. }
  45287. // Auto start
  45288. if (parsedParticleSystem.preventAutoStart) {
  45289. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45290. }
  45291. // Texture
  45292. if (parsedParticleSystem.textureName) {
  45293. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45294. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45295. }
  45296. // Emitter
  45297. if (parsedParticleSystem.emitterId) {
  45298. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45299. }
  45300. else {
  45301. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45302. }
  45303. // Animations
  45304. if (parsedParticleSystem.animations) {
  45305. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45306. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45307. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45308. }
  45309. }
  45310. if (parsedParticleSystem.autoAnimate) {
  45311. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45312. }
  45313. // Particle system
  45314. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45315. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45316. particleSystem.minSize = parsedParticleSystem.minSize;
  45317. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45318. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45319. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45320. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45321. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45322. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45323. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45324. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45325. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45326. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45327. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45328. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45329. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45330. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45331. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45332. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45333. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45334. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45335. if (!particleSystem.preventAutoStart) {
  45336. particleSystem.start();
  45337. }
  45338. return particleSystem;
  45339. };
  45340. // Statics
  45341. ParticleSystem.BLENDMODE_ONEONE = 0;
  45342. ParticleSystem.BLENDMODE_STANDARD = 1;
  45343. return ParticleSystem;
  45344. }());
  45345. BABYLON.ParticleSystem = ParticleSystem;
  45346. })(BABYLON || (BABYLON = {}));
  45347. //# sourceMappingURL=babylon.particleSystem.js.map
  45348. var BABYLON;
  45349. (function (BABYLON) {
  45350. var SolidParticle = /** @class */ (function () {
  45351. /**
  45352. * Creates a Solid Particle object.
  45353. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45354. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45355. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45356. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45357. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45358. * `shapeId` (integer) is the model shape identifier in the SPS.
  45359. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45360. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45361. */
  45362. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45363. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45364. this.idx = 0; // particle global index
  45365. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45366. this.position = BABYLON.Vector3.Zero(); // position
  45367. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45368. this.scaling = BABYLON.Vector3.One(); // scaling
  45369. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45370. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45371. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45372. this.alive = true; // alive
  45373. this.isVisible = true; // visibility
  45374. this._pos = 0; // index of this particle in the global "positions" array
  45375. this._ind = 0; // index of this particle in the global "indices" array
  45376. this.shapeId = 0; // model shape id
  45377. this.idxInShape = 0; // index of the particle in its shape id
  45378. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45379. this.idx = particleIndex;
  45380. this._pos = positionIndex;
  45381. this._ind = indiceIndex;
  45382. this._model = model;
  45383. this.shapeId = shapeId;
  45384. this.idxInShape = idxInShape;
  45385. this._sps = sps;
  45386. if (modelBoundingInfo) {
  45387. this._modelBoundingInfo = modelBoundingInfo;
  45388. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45389. }
  45390. }
  45391. Object.defineProperty(SolidParticle.prototype, "scale", {
  45392. /**
  45393. * legacy support, changed scale to scaling
  45394. */
  45395. get: function () {
  45396. return this.scaling;
  45397. },
  45398. set: function (scale) {
  45399. this.scaling = scale;
  45400. },
  45401. enumerable: true,
  45402. configurable: true
  45403. });
  45404. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45405. /**
  45406. * legacy support, changed quaternion to rotationQuaternion
  45407. */
  45408. get: function () {
  45409. return this.rotationQuaternion;
  45410. },
  45411. set: function (q) {
  45412. this.rotationQuaternion = q;
  45413. },
  45414. enumerable: true,
  45415. configurable: true
  45416. });
  45417. /**
  45418. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45419. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45420. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45421. */
  45422. SolidParticle.prototype.intersectsMesh = function (target) {
  45423. if (!this._boundingInfo || !target._boundingInfo) {
  45424. return false;
  45425. }
  45426. if (this._sps._bSphereOnly) {
  45427. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45428. }
  45429. return this._boundingInfo.intersects(target._boundingInfo, false);
  45430. };
  45431. return SolidParticle;
  45432. }());
  45433. BABYLON.SolidParticle = SolidParticle;
  45434. var ModelShape = /** @class */ (function () {
  45435. /**
  45436. * 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.
  45437. * SPS internal tool, don't use it manually.
  45438. */
  45439. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45440. this._indicesLength = 0; // length of the shape in the model indices array
  45441. this.shapeID = id;
  45442. this._shape = shape;
  45443. this._indicesLength = indicesLength;
  45444. this._shapeUV = shapeUV;
  45445. this._positionFunction = posFunction;
  45446. this._vertexFunction = vtxFunction;
  45447. }
  45448. return ModelShape;
  45449. }());
  45450. BABYLON.ModelShape = ModelShape;
  45451. var DepthSortedParticle = /** @class */ (function () {
  45452. function DepthSortedParticle() {
  45453. this.ind = 0; // index of the particle in the "indices" array
  45454. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45455. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45456. }
  45457. return DepthSortedParticle;
  45458. }());
  45459. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45460. })(BABYLON || (BABYLON = {}));
  45461. //# sourceMappingURL=babylon.solidParticle.js.map
  45462. var BABYLON;
  45463. (function (BABYLON) {
  45464. /**
  45465. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45466. */
  45467. var SolidParticleSystem = /** @class */ (function () {
  45468. /**
  45469. * Creates a SPS (Solid Particle System) object.
  45470. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45471. * `scene` (Scene) is the scene in which the SPS is added.
  45472. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45473. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45474. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45475. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45476. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45477. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45478. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45479. */
  45480. function SolidParticleSystem(name, scene, options) {
  45481. // public members
  45482. /**
  45483. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45484. * Example : var p = SPS.particles[i];
  45485. */
  45486. this.particles = new Array();
  45487. /**
  45488. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45489. */
  45490. this.nbParticles = 0;
  45491. /**
  45492. * If the particles must ever face the camera (default false). Useful for planar particles.
  45493. */
  45494. this.billboard = false;
  45495. /**
  45496. * Recompute normals when adding a shape
  45497. */
  45498. this.recomputeNormals = true;
  45499. /**
  45500. * This a counter ofr your own usage. It's not set by any SPS functions.
  45501. */
  45502. this.counter = 0;
  45503. /**
  45504. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45505. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45506. */
  45507. this.vars = {};
  45508. this._positions = new Array();
  45509. this._indices = new Array();
  45510. this._normals = new Array();
  45511. this._colors = new Array();
  45512. this._uvs = new Array();
  45513. this._index = 0; // indices index
  45514. this._updatable = true;
  45515. this._pickable = false;
  45516. this._isVisibilityBoxLocked = false;
  45517. this._alwaysVisible = false;
  45518. this._depthSort = false;
  45519. this._shapeCounter = 0;
  45520. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45521. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45522. this._computeParticleColor = true;
  45523. this._computeParticleTexture = true;
  45524. this._computeParticleRotation = true;
  45525. this._computeParticleVertex = false;
  45526. this._computeBoundingBox = false;
  45527. this._depthSortParticles = true;
  45528. this._cam_axisZ = BABYLON.Vector3.Zero();
  45529. this._cam_axisY = BABYLON.Vector3.Zero();
  45530. this._cam_axisX = BABYLON.Vector3.Zero();
  45531. this._axisZ = BABYLON.Axis.Z;
  45532. this._camDir = BABYLON.Vector3.Zero();
  45533. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45534. this._rotMatrix = new BABYLON.Matrix();
  45535. this._invertMatrix = new BABYLON.Matrix();
  45536. this._rotated = BABYLON.Vector3.Zero();
  45537. this._quaternion = new BABYLON.Quaternion();
  45538. this._vertex = BABYLON.Vector3.Zero();
  45539. this._normal = BABYLON.Vector3.Zero();
  45540. this._yaw = 0.0;
  45541. this._pitch = 0.0;
  45542. this._roll = 0.0;
  45543. this._halfroll = 0.0;
  45544. this._halfpitch = 0.0;
  45545. this._halfyaw = 0.0;
  45546. this._sinRoll = 0.0;
  45547. this._cosRoll = 0.0;
  45548. this._sinPitch = 0.0;
  45549. this._cosPitch = 0.0;
  45550. this._sinYaw = 0.0;
  45551. this._cosYaw = 0.0;
  45552. this._mustUnrotateFixedNormals = false;
  45553. this._minimum = BABYLON.Tmp.Vector3[0];
  45554. this._maximum = BABYLON.Tmp.Vector3[1];
  45555. this._minBbox = BABYLON.Tmp.Vector3[4];
  45556. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45557. this._particlesIntersect = false;
  45558. this._depthSortFunction = function (p1, p2) {
  45559. return (p2.sqDistance - p1.sqDistance);
  45560. };
  45561. this._needs32Bits = false;
  45562. this._bSphereOnly = false;
  45563. this._bSphereRadiusFactor = 1.0;
  45564. this.name = name;
  45565. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45566. this._camera = scene.activeCamera;
  45567. this._pickable = options ? options.isPickable : false;
  45568. this._depthSort = options ? options.enableDepthSort : false;
  45569. this._particlesIntersect = options ? options.particleIntersection : false;
  45570. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45571. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45572. if (options && options.updatable) {
  45573. this._updatable = options.updatable;
  45574. }
  45575. else {
  45576. this._updatable = true;
  45577. }
  45578. if (this._pickable) {
  45579. this.pickedParticles = [];
  45580. }
  45581. if (this._depthSort) {
  45582. this.depthSortedParticles = [];
  45583. }
  45584. }
  45585. /**
  45586. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45587. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45588. */
  45589. SolidParticleSystem.prototype.buildMesh = function () {
  45590. if (this.nbParticles === 0) {
  45591. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45592. this.addShape(triangle, 1);
  45593. triangle.dispose();
  45594. }
  45595. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45596. this._positions32 = new Float32Array(this._positions);
  45597. this._uvs32 = new Float32Array(this._uvs);
  45598. this._colors32 = new Float32Array(this._colors);
  45599. if (this.recomputeNormals) {
  45600. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45601. }
  45602. this._normals32 = new Float32Array(this._normals);
  45603. this._fixedNormal32 = new Float32Array(this._normals);
  45604. if (this._mustUnrotateFixedNormals) {
  45605. this._unrotateFixedNormals();
  45606. }
  45607. var vertexData = new BABYLON.VertexData();
  45608. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45609. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45610. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45611. if (this._uvs32) {
  45612. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45613. ;
  45614. }
  45615. if (this._colors32) {
  45616. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45617. }
  45618. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45619. vertexData.applyToMesh(mesh, this._updatable);
  45620. this.mesh = mesh;
  45621. this.mesh.isPickable = this._pickable;
  45622. // free memory
  45623. if (!this._depthSort) {
  45624. this._indices = null;
  45625. }
  45626. this._positions = null;
  45627. this._normals = null;
  45628. this._uvs = null;
  45629. this._colors = null;
  45630. if (!this._updatable) {
  45631. this.particles.length = 0;
  45632. }
  45633. return mesh;
  45634. };
  45635. /**
  45636. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45637. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45638. * Thus the particles generated from `digest()` have their property `position` set yet.
  45639. * `mesh` ( Mesh ) is the mesh to be digested
  45640. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45641. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45642. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45643. */
  45644. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45645. var size = (options && options.facetNb) || 1;
  45646. var number = (options && options.number) || 0;
  45647. var delta = (options && options.delta) || 0;
  45648. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45649. var meshInd = mesh.getIndices();
  45650. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45651. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45652. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45653. var f = 0; // facet counter
  45654. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45655. // compute size from number
  45656. if (number) {
  45657. number = (number > totalFacets) ? totalFacets : number;
  45658. size = Math.round(totalFacets / number);
  45659. delta = 0;
  45660. }
  45661. else {
  45662. size = (size > totalFacets) ? totalFacets : size;
  45663. }
  45664. var facetPos = []; // submesh positions
  45665. var facetInd = []; // submesh indices
  45666. var facetUV = []; // submesh UV
  45667. var facetCol = []; // submesh colors
  45668. var barycenter = BABYLON.Tmp.Vector3[0];
  45669. var sizeO = size;
  45670. while (f < totalFacets) {
  45671. size = sizeO + Math.floor((1 + delta) * Math.random());
  45672. if (f > totalFacets - size) {
  45673. size = totalFacets - f;
  45674. }
  45675. // reset temp arrays
  45676. facetPos.length = 0;
  45677. facetInd.length = 0;
  45678. facetUV.length = 0;
  45679. facetCol.length = 0;
  45680. // iterate over "size" facets
  45681. var fi = 0;
  45682. for (var j = f * 3; j < (f + size) * 3; j++) {
  45683. facetInd.push(fi);
  45684. var i = meshInd[j];
  45685. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45686. if (meshUV) {
  45687. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45688. }
  45689. if (meshCol) {
  45690. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45691. }
  45692. fi++;
  45693. }
  45694. // create a model shape for each single particle
  45695. var idx = this.nbParticles;
  45696. var shape = this._posToShape(facetPos);
  45697. var shapeUV = this._uvsToShapeUV(facetUV);
  45698. // compute the barycenter of the shape
  45699. var v;
  45700. for (v = 0; v < shape.length; v++) {
  45701. barycenter.addInPlace(shape[v]);
  45702. }
  45703. barycenter.scaleInPlace(1 / shape.length);
  45704. // shift the shape from its barycenter to the origin
  45705. for (v = 0; v < shape.length; v++) {
  45706. shape[v].subtractInPlace(barycenter);
  45707. }
  45708. var bInfo;
  45709. if (this._particlesIntersect) {
  45710. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45711. }
  45712. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45713. // add the particle in the SPS
  45714. var currentPos = this._positions.length;
  45715. var currentInd = this._indices.length;
  45716. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45717. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45718. // initialize the particle position
  45719. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45720. this._index += shape.length;
  45721. idx++;
  45722. this.nbParticles++;
  45723. this._shapeCounter++;
  45724. f += size;
  45725. }
  45726. return this;
  45727. };
  45728. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45729. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45730. var index = 0;
  45731. var idx = 0;
  45732. for (var p = 0; p < this.particles.length; p++) {
  45733. this._particle = this.particles[p];
  45734. this._shape = this._particle._model._shape;
  45735. if (this._particle.rotationQuaternion) {
  45736. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45737. }
  45738. else {
  45739. this._yaw = this._particle.rotation.y;
  45740. this._pitch = this._particle.rotation.x;
  45741. this._roll = this._particle.rotation.z;
  45742. this._quaternionRotationYPR();
  45743. }
  45744. this._quaternionToRotationMatrix();
  45745. this._rotMatrix.invertToRef(this._invertMatrix);
  45746. for (var pt = 0; pt < this._shape.length; pt++) {
  45747. idx = index + pt * 3;
  45748. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45749. this._fixedNormal32[idx] = this._normal.x;
  45750. this._fixedNormal32[idx + 1] = this._normal.y;
  45751. this._fixedNormal32[idx + 2] = this._normal.z;
  45752. }
  45753. index = idx + 3;
  45754. }
  45755. };
  45756. //reset copy
  45757. SolidParticleSystem.prototype._resetCopy = function () {
  45758. this._copy.position.x = 0;
  45759. this._copy.position.y = 0;
  45760. this._copy.position.z = 0;
  45761. this._copy.rotation.x = 0;
  45762. this._copy.rotation.y = 0;
  45763. this._copy.rotation.z = 0;
  45764. this._copy.rotationQuaternion = null;
  45765. this._copy.scaling.x = 1.0;
  45766. this._copy.scaling.y = 1.0;
  45767. this._copy.scaling.z = 1.0;
  45768. this._copy.uvs.x = 0;
  45769. this._copy.uvs.y = 0;
  45770. this._copy.uvs.z = 1.0;
  45771. this._copy.uvs.w = 1.0;
  45772. this._copy.color = null;
  45773. };
  45774. // _meshBuilder : inserts the shape model in the global SPS mesh
  45775. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45776. var i;
  45777. var u = 0;
  45778. var c = 0;
  45779. var n = 0;
  45780. this._resetCopy();
  45781. if (options && options.positionFunction) {
  45782. options.positionFunction(this._copy, idx, idxInShape);
  45783. this._mustUnrotateFixedNormals = true;
  45784. }
  45785. if (this._copy.rotationQuaternion) {
  45786. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45787. }
  45788. else {
  45789. this._yaw = this._copy.rotation.y;
  45790. this._pitch = this._copy.rotation.x;
  45791. this._roll = this._copy.rotation.z;
  45792. this._quaternionRotationYPR();
  45793. }
  45794. this._quaternionToRotationMatrix();
  45795. for (i = 0; i < shape.length; i++) {
  45796. this._vertex.x = shape[i].x;
  45797. this._vertex.y = shape[i].y;
  45798. this._vertex.z = shape[i].z;
  45799. if (options && options.vertexFunction) {
  45800. options.vertexFunction(this._copy, this._vertex, i);
  45801. }
  45802. this._vertex.x *= this._copy.scaling.x;
  45803. this._vertex.y *= this._copy.scaling.y;
  45804. this._vertex.z *= this._copy.scaling.z;
  45805. this._vertex.x += this._copy.pivot.x;
  45806. this._vertex.y += this._copy.pivot.y;
  45807. this._vertex.z += this._copy.pivot.z;
  45808. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45809. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45810. if (meshUV) {
  45811. 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);
  45812. u += 2;
  45813. }
  45814. if (this._copy.color) {
  45815. this._color = this._copy.color;
  45816. }
  45817. else if (meshCol && meshCol[c] !== undefined) {
  45818. this._color.r = meshCol[c];
  45819. this._color.g = meshCol[c + 1];
  45820. this._color.b = meshCol[c + 2];
  45821. this._color.a = meshCol[c + 3];
  45822. }
  45823. else {
  45824. this._color.r = 1.0;
  45825. this._color.g = 1.0;
  45826. this._color.b = 1.0;
  45827. this._color.a = 1.0;
  45828. }
  45829. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45830. c += 4;
  45831. if (!this.recomputeNormals && meshNor) {
  45832. this._normal.x = meshNor[n];
  45833. this._normal.y = meshNor[n + 1];
  45834. this._normal.z = meshNor[n + 2];
  45835. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45836. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45837. n += 3;
  45838. }
  45839. }
  45840. for (i = 0; i < meshInd.length; i++) {
  45841. var current_ind = p + meshInd[i];
  45842. indices.push(current_ind);
  45843. if (current_ind > 65535) {
  45844. this._needs32Bits = true;
  45845. }
  45846. }
  45847. if (this._pickable) {
  45848. var nbfaces = meshInd.length / 3;
  45849. for (i = 0; i < nbfaces; i++) {
  45850. this.pickedParticles.push({ idx: idx, faceId: i });
  45851. }
  45852. }
  45853. if (this._depthSort) {
  45854. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45855. }
  45856. return this._copy;
  45857. };
  45858. // returns a shape array from positions array
  45859. SolidParticleSystem.prototype._posToShape = function (positions) {
  45860. var shape = [];
  45861. for (var i = 0; i < positions.length; i += 3) {
  45862. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45863. }
  45864. return shape;
  45865. };
  45866. // returns a shapeUV array from a Vector4 uvs
  45867. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45868. var shapeUV = [];
  45869. if (uvs) {
  45870. for (var i = 0; i < uvs.length; i++)
  45871. shapeUV.push(uvs[i]);
  45872. }
  45873. return shapeUV;
  45874. };
  45875. // adds a new particle object in the particles array
  45876. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45877. if (bInfo === void 0) { bInfo = null; }
  45878. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45879. this.particles.push(sp);
  45880. return sp;
  45881. };
  45882. /**
  45883. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45884. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45885. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45886. * `nb` (positive integer) the number of particles to be created from this model
  45887. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45888. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45889. */
  45890. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45891. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45892. var meshInd = mesh.getIndices();
  45893. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45894. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45895. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45896. var bbInfo;
  45897. if (this._particlesIntersect) {
  45898. bbInfo = mesh.getBoundingInfo();
  45899. }
  45900. var shape = this._posToShape(meshPos);
  45901. var shapeUV = this._uvsToShapeUV(meshUV);
  45902. var posfunc = options ? options.positionFunction : null;
  45903. var vtxfunc = options ? options.vertexFunction : null;
  45904. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45905. // particles
  45906. var sp;
  45907. var currentCopy;
  45908. var idx = this.nbParticles;
  45909. for (var i = 0; i < nb; i++) {
  45910. var currentPos = this._positions.length;
  45911. var currentInd = this._indices.length;
  45912. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45913. if (this._updatable) {
  45914. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45915. sp.position.copyFrom(currentCopy.position);
  45916. sp.rotation.copyFrom(currentCopy.rotation);
  45917. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45918. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45919. }
  45920. if (currentCopy.color && sp.color) {
  45921. sp.color.copyFrom(currentCopy.color);
  45922. }
  45923. sp.scaling.copyFrom(currentCopy.scaling);
  45924. sp.uvs.copyFrom(currentCopy.uvs);
  45925. }
  45926. this._index += shape.length;
  45927. idx++;
  45928. }
  45929. this.nbParticles += nb;
  45930. this._shapeCounter++;
  45931. return this._shapeCounter - 1;
  45932. };
  45933. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45934. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45935. this._resetCopy();
  45936. if (particle._model._positionFunction) {
  45937. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45938. }
  45939. if (this._copy.rotationQuaternion) {
  45940. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45941. }
  45942. else {
  45943. this._yaw = this._copy.rotation.y;
  45944. this._pitch = this._copy.rotation.x;
  45945. this._roll = this._copy.rotation.z;
  45946. this._quaternionRotationYPR();
  45947. }
  45948. this._quaternionToRotationMatrix();
  45949. this._shape = particle._model._shape;
  45950. for (var pt = 0; pt < this._shape.length; pt++) {
  45951. this._vertex.x = this._shape[pt].x;
  45952. this._vertex.y = this._shape[pt].y;
  45953. this._vertex.z = this._shape[pt].z;
  45954. if (particle._model._vertexFunction) {
  45955. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45956. }
  45957. this._vertex.x *= this._copy.scaling.x;
  45958. this._vertex.y *= this._copy.scaling.y;
  45959. this._vertex.z *= this._copy.scaling.z;
  45960. this._vertex.x += this._copy.pivot.x;
  45961. this._vertex.y += this._copy.pivot.y;
  45962. this._vertex.z += this._copy.pivot.z;
  45963. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45964. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45965. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45966. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45967. }
  45968. particle.position.x = 0.0;
  45969. particle.position.y = 0.0;
  45970. particle.position.z = 0.0;
  45971. particle.rotation.x = 0.0;
  45972. particle.rotation.y = 0.0;
  45973. particle.rotation.z = 0.0;
  45974. particle.rotationQuaternion = null;
  45975. particle.scaling.x = 1.0;
  45976. particle.scaling.y = 1.0;
  45977. particle.scaling.z = 1.0;
  45978. };
  45979. /**
  45980. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45981. * Returns the SPS.
  45982. */
  45983. SolidParticleSystem.prototype.rebuildMesh = function () {
  45984. for (var p = 0; p < this.particles.length; p++) {
  45985. this._rebuildParticle(this.particles[p]);
  45986. }
  45987. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45988. return this;
  45989. };
  45990. /**
  45991. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45992. * This method calls `updateParticle()` for each particle of the SPS.
  45993. * For an animated SPS, it is usually called within the render loop.
  45994. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45995. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45996. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45997. * Returns the SPS.
  45998. */
  45999. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46000. if (start === void 0) { start = 0; }
  46001. if (end === void 0) { end = this.nbParticles - 1; }
  46002. if (update === void 0) { update = true; }
  46003. if (!this._updatable) {
  46004. return this;
  46005. }
  46006. // custom beforeUpdate
  46007. this.beforeUpdateParticles(start, end, update);
  46008. this._cam_axisX.x = 1.0;
  46009. this._cam_axisX.y = 0.0;
  46010. this._cam_axisX.z = 0.0;
  46011. this._cam_axisY.x = 0.0;
  46012. this._cam_axisY.y = 1.0;
  46013. this._cam_axisY.z = 0.0;
  46014. this._cam_axisZ.x = 0.0;
  46015. this._cam_axisZ.y = 0.0;
  46016. this._cam_axisZ.z = 1.0;
  46017. // cases when the World Matrix is to be computed first
  46018. if (this.billboard || this._depthSort) {
  46019. this.mesh.computeWorldMatrix(true);
  46020. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46021. }
  46022. // if the particles will always face the camera
  46023. if (this.billboard) {
  46024. // compute the camera position and un-rotate it by the current mesh rotation
  46025. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46026. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46027. this._cam_axisZ.normalize();
  46028. // same for camera up vector extracted from the cam view matrix
  46029. var view = this._camera.getViewMatrix(true);
  46030. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46031. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46032. this._cam_axisY.normalize();
  46033. this._cam_axisX.normalize();
  46034. }
  46035. // if depthSort, compute the camera global position in the mesh local system
  46036. if (this._depthSort) {
  46037. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46038. }
  46039. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46040. var idx = 0; // current position index in the global array positions32
  46041. var index = 0; // position start index in the global array positions32 of the current particle
  46042. var colidx = 0; // current color index in the global array colors32
  46043. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46044. var uvidx = 0; // current uv index in the global array uvs32
  46045. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46046. var pt = 0; // current index in the particle model shape
  46047. if (this.mesh.isFacetDataEnabled) {
  46048. this._computeBoundingBox = true;
  46049. }
  46050. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46051. if (this._computeBoundingBox) {
  46052. if (start == 0 && end == this.nbParticles - 1) {
  46053. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46054. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46055. }
  46056. else {
  46057. if (this.mesh._boundingInfo) {
  46058. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46059. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46060. }
  46061. }
  46062. }
  46063. // particle loop
  46064. index = this.particles[start]._pos;
  46065. var vpos = (index / 3) | 0;
  46066. colorIndex = vpos * 4;
  46067. uvIndex = vpos * 2;
  46068. for (var p = start; p <= end; p++) {
  46069. this._particle = this.particles[p];
  46070. this._shape = this._particle._model._shape;
  46071. this._shapeUV = this._particle._model._shapeUV;
  46072. // call to custom user function to update the particle properties
  46073. this.updateParticle(this._particle);
  46074. // camera-particle distance for depth sorting
  46075. if (this._depthSort && this._depthSortParticles) {
  46076. var dsp = this.depthSortedParticles[p];
  46077. dsp.ind = this._particle._ind;
  46078. dsp.indicesLength = this._particle._model._indicesLength;
  46079. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46080. }
  46081. // skip the computations for inactive or already invisible particles
  46082. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46083. // increment indexes for the next particle
  46084. pt = this._shape.length;
  46085. index += pt * 3;
  46086. colorIndex += pt * 4;
  46087. uvIndex += pt * 2;
  46088. continue;
  46089. }
  46090. if (this._particle.isVisible) {
  46091. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46092. // particle rotation matrix
  46093. if (this.billboard) {
  46094. this._particle.rotation.x = 0.0;
  46095. this._particle.rotation.y = 0.0;
  46096. }
  46097. if (this._computeParticleRotation || this.billboard) {
  46098. if (this._particle.rotationQuaternion) {
  46099. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46100. }
  46101. else {
  46102. this._yaw = this._particle.rotation.y;
  46103. this._pitch = this._particle.rotation.x;
  46104. this._roll = this._particle.rotation.z;
  46105. this._quaternionRotationYPR();
  46106. }
  46107. this._quaternionToRotationMatrix();
  46108. }
  46109. // particle vertex loop
  46110. for (pt = 0; pt < this._shape.length; pt++) {
  46111. idx = index + pt * 3;
  46112. colidx = colorIndex + pt * 4;
  46113. uvidx = uvIndex + pt * 2;
  46114. this._vertex.x = this._shape[pt].x;
  46115. this._vertex.y = this._shape[pt].y;
  46116. this._vertex.z = this._shape[pt].z;
  46117. if (this._computeParticleVertex) {
  46118. this.updateParticleVertex(this._particle, this._vertex, pt);
  46119. }
  46120. // positions
  46121. this._vertex.x *= this._particle.scaling.x;
  46122. this._vertex.y *= this._particle.scaling.y;
  46123. this._vertex.z *= this._particle.scaling.z;
  46124. this._vertex.x += this._particle.pivot.x;
  46125. this._vertex.y += this._particle.pivot.y;
  46126. this._vertex.z += this._particle.pivot.z;
  46127. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46128. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46129. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46130. 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;
  46131. 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;
  46132. 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;
  46133. if (this._computeBoundingBox) {
  46134. if (this._positions32[idx] < this._minimum.x) {
  46135. this._minimum.x = this._positions32[idx];
  46136. }
  46137. if (this._positions32[idx] > this._maximum.x) {
  46138. this._maximum.x = this._positions32[idx];
  46139. }
  46140. if (this._positions32[idx + 1] < this._minimum.y) {
  46141. this._minimum.y = this._positions32[idx + 1];
  46142. }
  46143. if (this._positions32[idx + 1] > this._maximum.y) {
  46144. this._maximum.y = this._positions32[idx + 1];
  46145. }
  46146. if (this._positions32[idx + 2] < this._minimum.z) {
  46147. this._minimum.z = this._positions32[idx + 2];
  46148. }
  46149. if (this._positions32[idx + 2] > this._maximum.z) {
  46150. this._maximum.z = this._positions32[idx + 2];
  46151. }
  46152. }
  46153. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46154. if (!this._computeParticleVertex) {
  46155. this._normal.x = this._fixedNormal32[idx];
  46156. this._normal.y = this._fixedNormal32[idx + 1];
  46157. this._normal.z = this._fixedNormal32[idx + 2];
  46158. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46159. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46160. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46161. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46162. 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;
  46163. 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;
  46164. }
  46165. if (this._computeParticleColor && this._particle.color) {
  46166. this._colors32[colidx] = this._particle.color.r;
  46167. this._colors32[colidx + 1] = this._particle.color.g;
  46168. this._colors32[colidx + 2] = this._particle.color.b;
  46169. this._colors32[colidx + 3] = this._particle.color.a;
  46170. }
  46171. if (this._computeParticleTexture) {
  46172. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46173. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46174. }
  46175. }
  46176. }
  46177. else {
  46178. this._particle._stillInvisible = true; // mark the particle as invisible
  46179. for (pt = 0; pt < this._shape.length; pt++) {
  46180. idx = index + pt * 3;
  46181. colidx = colorIndex + pt * 4;
  46182. uvidx = uvIndex + pt * 2;
  46183. this._positions32[idx] = 0.0;
  46184. this._positions32[idx + 1] = 0.0;
  46185. this._positions32[idx + 2] = 0.0;
  46186. this._normals32[idx] = 0.0;
  46187. this._normals32[idx + 1] = 0.0;
  46188. this._normals32[idx + 2] = 0.0;
  46189. if (this._computeParticleColor && this._particle.color) {
  46190. this._colors32[colidx] = this._particle.color.r;
  46191. this._colors32[colidx + 1] = this._particle.color.g;
  46192. this._colors32[colidx + 2] = this._particle.color.b;
  46193. this._colors32[colidx + 3] = this._particle.color.a;
  46194. }
  46195. if (this._computeParticleTexture) {
  46196. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46197. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46198. }
  46199. }
  46200. }
  46201. // if the particle intersections must be computed : update the bbInfo
  46202. if (this._particlesIntersect) {
  46203. var bInfo = this._particle._boundingInfo;
  46204. var bBox = bInfo.boundingBox;
  46205. var bSphere = bInfo.boundingSphere;
  46206. if (!this._bSphereOnly) {
  46207. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46208. for (var b = 0; b < bBox.vectors.length; b++) {
  46209. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46210. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46211. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46212. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46213. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46214. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46215. 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;
  46216. 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;
  46217. 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;
  46218. }
  46219. bBox._update(this.mesh._worldMatrix);
  46220. }
  46221. // place and scale the particle bouding sphere in the SPS local system, then update it
  46222. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46223. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46224. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46225. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46226. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46227. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46228. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46229. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46230. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46231. 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));
  46232. bSphere._update(this.mesh._worldMatrix);
  46233. }
  46234. // increment indexes for the next particle
  46235. index = idx + 3;
  46236. colorIndex = colidx + 4;
  46237. uvIndex = uvidx + 2;
  46238. }
  46239. // if the VBO must be updated
  46240. if (update) {
  46241. if (this._computeParticleColor) {
  46242. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46243. }
  46244. if (this._computeParticleTexture) {
  46245. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46246. }
  46247. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46248. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46249. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46250. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46251. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46252. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46253. for (var i = 0; i < this._normals32.length; i++) {
  46254. this._fixedNormal32[i] = this._normals32[i];
  46255. }
  46256. }
  46257. if (!this.mesh.areNormalsFrozen) {
  46258. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46259. }
  46260. }
  46261. if (this._depthSort && this._depthSortParticles) {
  46262. this.depthSortedParticles.sort(this._depthSortFunction);
  46263. var dspl = this.depthSortedParticles.length;
  46264. var sorted = 0;
  46265. var lind = 0;
  46266. var sind = 0;
  46267. var sid = 0;
  46268. for (sorted = 0; sorted < dspl; sorted++) {
  46269. lind = this.depthSortedParticles[sorted].indicesLength;
  46270. sind = this.depthSortedParticles[sorted].ind;
  46271. for (var i = 0; i < lind; i++) {
  46272. this._indices32[sid] = this._indices[sind + i];
  46273. sid++;
  46274. }
  46275. }
  46276. this.mesh.updateIndices(this._indices32);
  46277. }
  46278. }
  46279. if (this._computeBoundingBox) {
  46280. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46281. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46282. }
  46283. this.afterUpdateParticles(start, end, update);
  46284. return this;
  46285. };
  46286. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46287. this._halfroll = this._roll * 0.5;
  46288. this._halfpitch = this._pitch * 0.5;
  46289. this._halfyaw = this._yaw * 0.5;
  46290. this._sinRoll = Math.sin(this._halfroll);
  46291. this._cosRoll = Math.cos(this._halfroll);
  46292. this._sinPitch = Math.sin(this._halfpitch);
  46293. this._cosPitch = Math.cos(this._halfpitch);
  46294. this._sinYaw = Math.sin(this._halfyaw);
  46295. this._cosYaw = Math.cos(this._halfyaw);
  46296. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46297. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46298. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46299. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46300. };
  46301. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46302. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46303. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46304. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46305. this._rotMatrix.m[3] = 0;
  46306. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46307. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46308. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46309. this._rotMatrix.m[7] = 0;
  46310. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46311. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46312. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46313. this._rotMatrix.m[11] = 0;
  46314. this._rotMatrix.m[12] = 0;
  46315. this._rotMatrix.m[13] = 0;
  46316. this._rotMatrix.m[14] = 0;
  46317. this._rotMatrix.m[15] = 1.0;
  46318. };
  46319. /**
  46320. * Disposes the SPS.
  46321. * Returns nothing.
  46322. */
  46323. SolidParticleSystem.prototype.dispose = function () {
  46324. this.mesh.dispose();
  46325. this.vars = null;
  46326. // drop references to internal big arrays for the GC
  46327. this._positions = null;
  46328. this._indices = null;
  46329. this._normals = null;
  46330. this._uvs = null;
  46331. this._colors = null;
  46332. this._indices32 = null;
  46333. this._positions32 = null;
  46334. this._normals32 = null;
  46335. this._fixedNormal32 = null;
  46336. this._uvs32 = null;
  46337. this._colors32 = null;
  46338. this.pickedParticles = null;
  46339. };
  46340. /**
  46341. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46342. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46343. * Returns the SPS.
  46344. */
  46345. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46346. if (!this._isVisibilityBoxLocked) {
  46347. this.mesh.refreshBoundingInfo();
  46348. }
  46349. return this;
  46350. };
  46351. /**
  46352. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46353. * @param size the size (float) of the visibility box
  46354. * note : this doesn't lock the SPS mesh bounding box.
  46355. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46356. */
  46357. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46358. var vis = size / 2;
  46359. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46360. };
  46361. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46362. // getter and setter
  46363. get: function () {
  46364. return this._alwaysVisible;
  46365. },
  46366. /**
  46367. * Sets the SPS as always visible or not
  46368. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46369. */
  46370. set: function (val) {
  46371. this._alwaysVisible = val;
  46372. this.mesh.alwaysSelectAsActiveMesh = val;
  46373. },
  46374. enumerable: true,
  46375. configurable: true
  46376. });
  46377. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46378. get: function () {
  46379. return this._isVisibilityBoxLocked;
  46380. },
  46381. /**
  46382. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46384. */
  46385. set: function (val) {
  46386. this._isVisibilityBoxLocked = val;
  46387. var boundingInfo = this.mesh.getBoundingInfo();
  46388. boundingInfo.isLocked = val;
  46389. },
  46390. enumerable: true,
  46391. configurable: true
  46392. });
  46393. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46394. // getters
  46395. get: function () {
  46396. return this._computeParticleRotation;
  46397. },
  46398. // Optimizer setters
  46399. /**
  46400. * Tells to `setParticles()` to compute the particle rotations or not.
  46401. * Default value : true. The SPS is faster when it's set to false.
  46402. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46403. */
  46404. set: function (val) {
  46405. this._computeParticleRotation = val;
  46406. },
  46407. enumerable: true,
  46408. configurable: true
  46409. });
  46410. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46411. get: function () {
  46412. return this._computeParticleColor;
  46413. },
  46414. /**
  46415. * Tells to `setParticles()` to compute the particle colors or not.
  46416. * Default value : true. The SPS is faster when it's set to false.
  46417. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46418. */
  46419. set: function (val) {
  46420. this._computeParticleColor = val;
  46421. },
  46422. enumerable: true,
  46423. configurable: true
  46424. });
  46425. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46426. get: function () {
  46427. return this._computeParticleTexture;
  46428. },
  46429. /**
  46430. * Tells to `setParticles()` to compute the particle textures or not.
  46431. * Default value : true. The SPS is faster when it's set to false.
  46432. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46433. */
  46434. set: function (val) {
  46435. this._computeParticleTexture = val;
  46436. },
  46437. enumerable: true,
  46438. configurable: true
  46439. });
  46440. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46441. get: function () {
  46442. return this._computeParticleVertex;
  46443. },
  46444. /**
  46445. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46446. * Default value : false. The SPS is faster when it's set to false.
  46447. * Note : the particle custom vertex positions aren't stored values.
  46448. */
  46449. set: function (val) {
  46450. this._computeParticleVertex = val;
  46451. },
  46452. enumerable: true,
  46453. configurable: true
  46454. });
  46455. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46456. get: function () {
  46457. return this._computeBoundingBox;
  46458. },
  46459. /**
  46460. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46461. */
  46462. set: function (val) {
  46463. this._computeBoundingBox = val;
  46464. },
  46465. enumerable: true,
  46466. configurable: true
  46467. });
  46468. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46469. get: function () {
  46470. return this._depthSortParticles;
  46471. },
  46472. /**
  46473. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46474. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46475. * Default : `true`
  46476. */
  46477. set: function (val) {
  46478. this._depthSortParticles = val;
  46479. },
  46480. enumerable: true,
  46481. configurable: true
  46482. });
  46483. // =======================================================================
  46484. // Particle behavior logic
  46485. // these following methods may be overwritten by the user to fit his needs
  46486. /**
  46487. * This function does nothing. It may be overwritten to set all the particle first values.
  46488. * The SPS doesn't call this function, you may have to call it by your own.
  46489. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46490. */
  46491. SolidParticleSystem.prototype.initParticles = function () {
  46492. };
  46493. /**
  46494. * This function does nothing. It may be overwritten to recycle a particle.
  46495. * The SPS doesn't call this function, you may have to call it by your own.
  46496. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46497. */
  46498. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46499. return particle;
  46500. };
  46501. /**
  46502. * Updates a particle : this function should be overwritten by the user.
  46503. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46504. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46505. * ex : just set a particle position or velocity and recycle conditions
  46506. */
  46507. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46508. return particle;
  46509. };
  46510. /**
  46511. * Updates a vertex of a particle : it can be overwritten by the user.
  46512. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46513. * @param particle the current particle
  46514. * @param vertex the current index of the current particle
  46515. * @param pt the index of the current vertex in the particle shape
  46516. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46517. * ex : just set a vertex particle position
  46518. */
  46519. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46520. return vertex;
  46521. };
  46522. /**
  46523. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46524. * This does nothing and may be overwritten by the user.
  46525. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46526. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46527. * @param update the boolean update value actually passed to setParticles()
  46528. */
  46529. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46530. };
  46531. /**
  46532. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46533. * This will be passed three parameters.
  46534. * This does nothing and may be overwritten by the user.
  46535. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46536. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46537. * @param update the boolean update value actually passed to setParticles()
  46538. */
  46539. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46540. };
  46541. return SolidParticleSystem;
  46542. }());
  46543. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46544. })(BABYLON || (BABYLON = {}));
  46545. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46546. var BABYLON;
  46547. (function (BABYLON) {
  46548. var GroundMesh = /** @class */ (function (_super) {
  46549. __extends(GroundMesh, _super);
  46550. function GroundMesh(name, scene) {
  46551. var _this = _super.call(this, name, scene) || this;
  46552. _this.generateOctree = false;
  46553. return _this;
  46554. }
  46555. GroundMesh.prototype.getClassName = function () {
  46556. return "GroundMesh";
  46557. };
  46558. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46559. get: function () {
  46560. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46566. get: function () {
  46567. return this._subdivisionsX;
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46573. get: function () {
  46574. return this._subdivisionsY;
  46575. },
  46576. enumerable: true,
  46577. configurable: true
  46578. });
  46579. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46580. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46581. this._subdivisionsX = chunksCount;
  46582. this._subdivisionsY = chunksCount;
  46583. this.subdivide(chunksCount);
  46584. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46585. };
  46586. /**
  46587. * Returns a height (y) value in the Worl system :
  46588. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46589. * Returns the ground y position if (x, z) are outside the ground surface.
  46590. */
  46591. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46592. var world = this.getWorldMatrix();
  46593. var invMat = BABYLON.Tmp.Matrix[5];
  46594. world.invertToRef(invMat);
  46595. var tmpVect = BABYLON.Tmp.Vector3[8];
  46596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46597. x = tmpVect.x;
  46598. z = tmpVect.z;
  46599. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46600. return this.position.y;
  46601. }
  46602. if (!this._heightQuads || this._heightQuads.length == 0) {
  46603. this._initHeightQuads();
  46604. this._computeHeightQuads();
  46605. }
  46606. var facet = this._getFacetAt(x, z);
  46607. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46608. // return y in the World system
  46609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46610. return tmpVect.y;
  46611. };
  46612. /**
  46613. * Returns a normalized vector (Vector3) orthogonal to the ground
  46614. * at the ground coordinates (x, z) expressed in the World system.
  46615. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46616. */
  46617. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46618. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46619. this.getNormalAtCoordinatesToRef(x, z, normal);
  46620. return normal;
  46621. };
  46622. /**
  46623. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46624. * at the ground coordinates (x, z) expressed in the World system.
  46625. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46626. * Returns the GroundMesh.
  46627. */
  46628. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46629. var world = this.getWorldMatrix();
  46630. var tmpMat = BABYLON.Tmp.Matrix[5];
  46631. world.invertToRef(tmpMat);
  46632. var tmpVect = BABYLON.Tmp.Vector3[8];
  46633. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46634. x = tmpVect.x;
  46635. z = tmpVect.z;
  46636. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46637. return this;
  46638. }
  46639. if (!this._heightQuads || this._heightQuads.length == 0) {
  46640. this._initHeightQuads();
  46641. this._computeHeightQuads();
  46642. }
  46643. var facet = this._getFacetAt(x, z);
  46644. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46645. return this;
  46646. };
  46647. /**
  46648. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46649. * if the ground has been updated.
  46650. * This can be used in the render loop.
  46651. * Returns the GroundMesh.
  46652. */
  46653. GroundMesh.prototype.updateCoordinateHeights = function () {
  46654. if (!this._heightQuads || this._heightQuads.length == 0) {
  46655. this._initHeightQuads();
  46656. }
  46657. this._computeHeightQuads();
  46658. return this;
  46659. };
  46660. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46661. GroundMesh.prototype._getFacetAt = function (x, z) {
  46662. // retrieve col and row from x, z coordinates in the ground local system
  46663. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46664. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46665. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46666. var facet;
  46667. if (z < quad.slope.x * x + quad.slope.y) {
  46668. facet = quad.facet1;
  46669. }
  46670. else {
  46671. facet = quad.facet2;
  46672. }
  46673. return facet;
  46674. };
  46675. // Creates and populates the heightMap array with "facet" elements :
  46676. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46677. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46678. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46679. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46680. // Returns the GroundMesh.
  46681. GroundMesh.prototype._initHeightQuads = function () {
  46682. var subdivisionsX = this._subdivisionsX;
  46683. var subdivisionsY = this._subdivisionsY;
  46684. this._heightQuads = new Array();
  46685. for (var row = 0; row < subdivisionsY; row++) {
  46686. for (var col = 0; col < subdivisionsX; col++) {
  46687. 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) };
  46688. this._heightQuads[row * subdivisionsX + col] = quad;
  46689. }
  46690. }
  46691. return this;
  46692. };
  46693. // Compute each quad element values and update the the heightMap array :
  46694. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46695. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46696. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46697. // Returns the GroundMesh.
  46698. GroundMesh.prototype._computeHeightQuads = function () {
  46699. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46700. if (!positions) {
  46701. return this;
  46702. }
  46703. var v1 = BABYLON.Tmp.Vector3[3];
  46704. var v2 = BABYLON.Tmp.Vector3[2];
  46705. var v3 = BABYLON.Tmp.Vector3[1];
  46706. var v4 = BABYLON.Tmp.Vector3[0];
  46707. var v1v2 = BABYLON.Tmp.Vector3[4];
  46708. var v1v3 = BABYLON.Tmp.Vector3[5];
  46709. var v1v4 = BABYLON.Tmp.Vector3[6];
  46710. var norm1 = BABYLON.Tmp.Vector3[7];
  46711. var norm2 = BABYLON.Tmp.Vector3[8];
  46712. var i = 0;
  46713. var j = 0;
  46714. var k = 0;
  46715. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46716. var h = 0;
  46717. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46718. var d2 = 0;
  46719. var subdivisionsX = this._subdivisionsX;
  46720. var subdivisionsY = this._subdivisionsY;
  46721. for (var row = 0; row < subdivisionsY; row++) {
  46722. for (var col = 0; col < subdivisionsX; col++) {
  46723. i = col * 3;
  46724. j = row * (subdivisionsX + 1) * 3;
  46725. k = (row + 1) * (subdivisionsX + 1) * 3;
  46726. v1.x = positions[j + i];
  46727. v1.y = positions[j + i + 1];
  46728. v1.z = positions[j + i + 2];
  46729. v2.x = positions[j + i + 3];
  46730. v2.y = positions[j + i + 4];
  46731. v2.z = positions[j + i + 5];
  46732. v3.x = positions[k + i];
  46733. v3.y = positions[k + i + 1];
  46734. v3.z = positions[k + i + 2];
  46735. v4.x = positions[k + i + 3];
  46736. v4.y = positions[k + i + 4];
  46737. v4.z = positions[k + i + 5];
  46738. // 2D slope V1V4
  46739. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46740. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46741. // facet equations :
  46742. // we compute each facet normal vector
  46743. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46744. // we compute the value d by applying the equation to v1 which belongs to the plane
  46745. // then we store the facet equation in a Vector4
  46746. v2.subtractToRef(v1, v1v2);
  46747. v3.subtractToRef(v1, v1v3);
  46748. v4.subtractToRef(v1, v1v4);
  46749. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46750. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46751. norm1.normalize();
  46752. norm2.normalize();
  46753. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46754. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46755. var quad = this._heightQuads[row * subdivisionsX + col];
  46756. quad.slope.copyFromFloats(cd, h);
  46757. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46758. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46759. }
  46760. }
  46761. return this;
  46762. };
  46763. GroundMesh.prototype.serialize = function (serializationObject) {
  46764. _super.prototype.serialize.call(this, serializationObject);
  46765. serializationObject.subdivisionsX = this._subdivisionsX;
  46766. serializationObject.subdivisionsY = this._subdivisionsY;
  46767. serializationObject.minX = this._minX;
  46768. serializationObject.maxX = this._maxX;
  46769. serializationObject.minZ = this._minZ;
  46770. serializationObject.maxZ = this._maxZ;
  46771. serializationObject.width = this._width;
  46772. serializationObject.height = this._height;
  46773. };
  46774. GroundMesh.Parse = function (parsedMesh, scene) {
  46775. var result = new GroundMesh(parsedMesh.name, scene);
  46776. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46777. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46778. result._minX = parsedMesh.minX;
  46779. result._maxX = parsedMesh.maxX;
  46780. result._minZ = parsedMesh.minZ;
  46781. result._maxZ = parsedMesh.maxZ;
  46782. result._width = parsedMesh.width;
  46783. result._height = parsedMesh.height;
  46784. return result;
  46785. };
  46786. return GroundMesh;
  46787. }(BABYLON.Mesh));
  46788. BABYLON.GroundMesh = GroundMesh;
  46789. })(BABYLON || (BABYLON = {}));
  46790. //# sourceMappingURL=babylon.groundMesh.js.map
  46791. var BABYLON;
  46792. (function (BABYLON) {
  46793. /**
  46794. * Creates an instance based on a source mesh.
  46795. */
  46796. var InstancedMesh = /** @class */ (function (_super) {
  46797. __extends(InstancedMesh, _super);
  46798. function InstancedMesh(name, source) {
  46799. var _this = _super.call(this, name, source.getScene()) || this;
  46800. source.instances.push(_this);
  46801. _this._sourceMesh = source;
  46802. _this.position.copyFrom(source.position);
  46803. _this.rotation.copyFrom(source.rotation);
  46804. _this.scaling.copyFrom(source.scaling);
  46805. if (source.rotationQuaternion) {
  46806. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46807. }
  46808. _this.infiniteDistance = source.infiniteDistance;
  46809. _this.setPivotMatrix(source.getPivotMatrix());
  46810. _this.refreshBoundingInfo();
  46811. _this._syncSubMeshes();
  46812. return _this;
  46813. }
  46814. /**
  46815. * Returns the string "InstancedMesh".
  46816. */
  46817. InstancedMesh.prototype.getClassName = function () {
  46818. return "InstancedMesh";
  46819. };
  46820. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46821. // Methods
  46822. get: function () {
  46823. return this._sourceMesh.receiveShadows;
  46824. },
  46825. enumerable: true,
  46826. configurable: true
  46827. });
  46828. Object.defineProperty(InstancedMesh.prototype, "material", {
  46829. get: function () {
  46830. return this._sourceMesh.material;
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46836. get: function () {
  46837. return this._sourceMesh.visibility;
  46838. },
  46839. enumerable: true,
  46840. configurable: true
  46841. });
  46842. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46843. get: function () {
  46844. return this._sourceMesh.skeleton;
  46845. },
  46846. enumerable: true,
  46847. configurable: true
  46848. });
  46849. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46850. get: function () {
  46851. return this._sourceMesh.renderingGroupId;
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. /**
  46857. * Returns the total number of vertices (integer).
  46858. */
  46859. InstancedMesh.prototype.getTotalVertices = function () {
  46860. return this._sourceMesh.getTotalVertices();
  46861. };
  46862. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46863. get: function () {
  46864. return this._sourceMesh;
  46865. },
  46866. enumerable: true,
  46867. configurable: true
  46868. });
  46869. /**
  46870. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46871. */
  46872. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46873. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46874. };
  46875. /**
  46876. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46877. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46878. * The `data` are either a numeric array either a Float32Array.
  46879. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46880. * 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).
  46881. * Note that a new underlying VertexBuffer object is created each call.
  46882. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46883. *
  46884. * Possible `kind` values :
  46885. * - BABYLON.VertexBuffer.PositionKind
  46886. * - BABYLON.VertexBuffer.UVKind
  46887. * - BABYLON.VertexBuffer.UV2Kind
  46888. * - BABYLON.VertexBuffer.UV3Kind
  46889. * - BABYLON.VertexBuffer.UV4Kind
  46890. * - BABYLON.VertexBuffer.UV5Kind
  46891. * - BABYLON.VertexBuffer.UV6Kind
  46892. * - BABYLON.VertexBuffer.ColorKind
  46893. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46894. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46895. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46896. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46897. *
  46898. * Returns the Mesh.
  46899. */
  46900. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46901. if (this.sourceMesh) {
  46902. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46903. }
  46904. return this.sourceMesh;
  46905. };
  46906. /**
  46907. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46908. * If the mesh has no geometry, it is simply returned as it is.
  46909. * The `data` are either a numeric array either a Float32Array.
  46910. * No new underlying VertexBuffer object is created.
  46911. * 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.
  46912. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46913. *
  46914. * Possible `kind` values :
  46915. * - BABYLON.VertexBuffer.PositionKind
  46916. * - BABYLON.VertexBuffer.UVKind
  46917. * - BABYLON.VertexBuffer.UV2Kind
  46918. * - BABYLON.VertexBuffer.UV3Kind
  46919. * - BABYLON.VertexBuffer.UV4Kind
  46920. * - BABYLON.VertexBuffer.UV5Kind
  46921. * - BABYLON.VertexBuffer.UV6Kind
  46922. * - BABYLON.VertexBuffer.ColorKind
  46923. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46924. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46925. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46926. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46927. *
  46928. * Returns the Mesh.
  46929. */
  46930. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46931. if (this.sourceMesh) {
  46932. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46933. }
  46934. return this.sourceMesh;
  46935. };
  46936. /**
  46937. * Sets the mesh indices.
  46938. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46939. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46940. * This method creates a new index buffer each call.
  46941. * Returns the Mesh.
  46942. */
  46943. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46944. if (totalVertices === void 0) { totalVertices = null; }
  46945. if (this.sourceMesh) {
  46946. this.sourceMesh.setIndices(indices, totalVertices);
  46947. }
  46948. return this.sourceMesh;
  46949. };
  46950. /**
  46951. * Boolean : True if the mesh owns the requested kind of data.
  46952. */
  46953. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46954. return this._sourceMesh.isVerticesDataPresent(kind);
  46955. };
  46956. /**
  46957. * Returns an array of indices (IndicesArray).
  46958. */
  46959. InstancedMesh.prototype.getIndices = function () {
  46960. return this._sourceMesh.getIndices();
  46961. };
  46962. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46963. get: function () {
  46964. return this._sourceMesh._positions;
  46965. },
  46966. enumerable: true,
  46967. configurable: true
  46968. });
  46969. /**
  46970. * Sets a new updated BoundingInfo to the mesh.
  46971. * Returns the mesh.
  46972. */
  46973. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46974. var meshBB = this._sourceMesh.getBoundingInfo();
  46975. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46976. this._updateBoundingInfo();
  46977. return this;
  46978. };
  46979. InstancedMesh.prototype._preActivate = function () {
  46980. if (this._currentLOD) {
  46981. this._currentLOD._preActivate();
  46982. }
  46983. return this;
  46984. };
  46985. InstancedMesh.prototype._activate = function (renderId) {
  46986. if (this._currentLOD) {
  46987. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46988. }
  46989. return this;
  46990. };
  46991. /**
  46992. * Returns the current associated LOD AbstractMesh.
  46993. */
  46994. InstancedMesh.prototype.getLOD = function (camera) {
  46995. if (!camera) {
  46996. return this;
  46997. }
  46998. var boundingInfo = this.getBoundingInfo();
  46999. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47000. if (this._currentLOD === this.sourceMesh) {
  47001. return this;
  47002. }
  47003. return this._currentLOD;
  47004. };
  47005. InstancedMesh.prototype._syncSubMeshes = function () {
  47006. this.releaseSubMeshes();
  47007. if (this._sourceMesh.subMeshes) {
  47008. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47009. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47010. }
  47011. }
  47012. return this;
  47013. };
  47014. InstancedMesh.prototype._generatePointsArray = function () {
  47015. return this._sourceMesh._generatePointsArray();
  47016. };
  47017. /**
  47018. * Creates a new InstancedMesh from the current mesh.
  47019. * - name (string) : the cloned mesh name
  47020. * - newParent (optional Node) : the optional Node to parent the clone to.
  47021. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47022. *
  47023. * Returns the clone.
  47024. */
  47025. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47026. var result = this._sourceMesh.createInstance(name);
  47027. // Deep copy
  47028. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47029. // Bounding info
  47030. this.refreshBoundingInfo();
  47031. // Parent
  47032. if (newParent) {
  47033. result.parent = newParent;
  47034. }
  47035. if (!doNotCloneChildren) {
  47036. // Children
  47037. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47038. var mesh = this.getScene().meshes[index];
  47039. if (mesh.parent === this) {
  47040. mesh.clone(mesh.name, result);
  47041. }
  47042. }
  47043. }
  47044. result.computeWorldMatrix(true);
  47045. return result;
  47046. };
  47047. /**
  47048. * Disposes the InstancedMesh.
  47049. * Returns nothing.
  47050. */
  47051. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47052. // Remove from mesh
  47053. var index = this._sourceMesh.instances.indexOf(this);
  47054. this._sourceMesh.instances.splice(index, 1);
  47055. _super.prototype.dispose.call(this, doNotRecurse);
  47056. };
  47057. return InstancedMesh;
  47058. }(BABYLON.AbstractMesh));
  47059. BABYLON.InstancedMesh = InstancedMesh;
  47060. })(BABYLON || (BABYLON = {}));
  47061. //# sourceMappingURL=babylon.instancedMesh.js.map
  47062. var BABYLON;
  47063. (function (BABYLON) {
  47064. var LinesMesh = /** @class */ (function (_super) {
  47065. __extends(LinesMesh, _super);
  47066. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47067. if (scene === void 0) { scene = null; }
  47068. if (parent === void 0) { parent = null; }
  47069. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47070. _this.useVertexColor = useVertexColor;
  47071. _this.useVertexAlpha = useVertexAlpha;
  47072. _this.color = new BABYLON.Color3(1, 1, 1);
  47073. _this.alpha = 1;
  47074. if (source) {
  47075. _this.color = source.color.clone();
  47076. _this.alpha = source.alpha;
  47077. _this.useVertexColor = source.useVertexColor;
  47078. _this.useVertexAlpha = source.useVertexAlpha;
  47079. }
  47080. _this._intersectionThreshold = 0.1;
  47081. var defines = [];
  47082. var options = {
  47083. attributes: [BABYLON.VertexBuffer.PositionKind],
  47084. uniforms: ["world", "viewProjection"],
  47085. needAlphaBlending: true,
  47086. defines: defines
  47087. };
  47088. if (useVertexAlpha === false) {
  47089. options.needAlphaBlending = false;
  47090. }
  47091. if (!useVertexColor) {
  47092. options.uniforms.push("color");
  47093. }
  47094. else {
  47095. options.defines.push("#define VERTEXCOLOR");
  47096. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47097. }
  47098. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47099. return _this;
  47100. }
  47101. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47102. /**
  47103. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47104. * This margin is expressed in world space coordinates, so its value may vary.
  47105. * Default value is 0.1
  47106. * @returns the intersection Threshold value.
  47107. */
  47108. get: function () {
  47109. return this._intersectionThreshold;
  47110. },
  47111. /**
  47112. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47113. * This margin is expressed in world space coordinates, so its value may vary.
  47114. * @param value the new threshold to apply
  47115. */
  47116. set: function (value) {
  47117. if (this._intersectionThreshold === value) {
  47118. return;
  47119. }
  47120. this._intersectionThreshold = value;
  47121. if (this.geometry) {
  47122. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47123. }
  47124. },
  47125. enumerable: true,
  47126. configurable: true
  47127. });
  47128. /**
  47129. * Returns the string "LineMesh"
  47130. */
  47131. LinesMesh.prototype.getClassName = function () {
  47132. return "LinesMesh";
  47133. };
  47134. Object.defineProperty(LinesMesh.prototype, "material", {
  47135. get: function () {
  47136. return this._colorShader;
  47137. },
  47138. set: function (value) {
  47139. // Do nothing
  47140. },
  47141. enumerable: true,
  47142. configurable: true
  47143. });
  47144. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47145. get: function () {
  47146. return false;
  47147. },
  47148. enumerable: true,
  47149. configurable: true
  47150. });
  47151. LinesMesh.prototype.createInstance = function (name) {
  47152. throw new Error("LinesMeshes do not support createInstance.");
  47153. };
  47154. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47155. if (!this._geometry) {
  47156. return this;
  47157. }
  47158. // VBOs
  47159. this._geometry._bind(this._colorShader.getEffect());
  47160. // Color
  47161. if (!this.useVertexColor) {
  47162. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47163. }
  47164. return this;
  47165. };
  47166. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47167. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47168. return this;
  47169. }
  47170. var engine = this.getScene().getEngine();
  47171. // Draw order
  47172. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  47173. return this;
  47174. };
  47175. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47176. this._colorShader.dispose();
  47177. _super.prototype.dispose.call(this, doNotRecurse);
  47178. };
  47179. /**
  47180. * Returns a new LineMesh object cloned from the current one.
  47181. */
  47182. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47183. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47184. };
  47185. return LinesMesh;
  47186. }(BABYLON.Mesh));
  47187. BABYLON.LinesMesh = LinesMesh;
  47188. })(BABYLON || (BABYLON = {}));
  47189. //# sourceMappingURL=babylon.linesMesh.js.map
  47190. var BABYLON;
  47191. (function (BABYLON) {
  47192. var ShaderMaterial = /** @class */ (function (_super) {
  47193. __extends(ShaderMaterial, _super);
  47194. function ShaderMaterial(name, scene, shaderPath, options) {
  47195. var _this = _super.call(this, name, scene) || this;
  47196. _this._textures = {};
  47197. _this._textureArrays = {};
  47198. _this._floats = {};
  47199. _this._floatsArrays = {};
  47200. _this._colors3 = {};
  47201. _this._colors3Arrays = {};
  47202. _this._colors4 = {};
  47203. _this._vectors2 = {};
  47204. _this._vectors3 = {};
  47205. _this._vectors4 = {};
  47206. _this._matrices = {};
  47207. _this._matrices3x3 = {};
  47208. _this._matrices2x2 = {};
  47209. _this._vectors2Arrays = {};
  47210. _this._vectors3Arrays = {};
  47211. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47212. _this._shaderPath = shaderPath;
  47213. options.needAlphaBlending = options.needAlphaBlending || false;
  47214. options.needAlphaTesting = options.needAlphaTesting || false;
  47215. options.attributes = options.attributes || ["position", "normal", "uv"];
  47216. options.uniforms = options.uniforms || ["worldViewProjection"];
  47217. options.uniformBuffers = options.uniformBuffers || [];
  47218. options.samplers = options.samplers || [];
  47219. options.defines = options.defines || [];
  47220. _this._options = options;
  47221. return _this;
  47222. }
  47223. ShaderMaterial.prototype.getClassName = function () {
  47224. return "ShaderMaterial";
  47225. };
  47226. ShaderMaterial.prototype.needAlphaBlending = function () {
  47227. return this._options.needAlphaBlending;
  47228. };
  47229. ShaderMaterial.prototype.needAlphaTesting = function () {
  47230. return this._options.needAlphaTesting;
  47231. };
  47232. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47233. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47234. this._options.uniforms.push(uniformName);
  47235. }
  47236. };
  47237. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47238. if (this._options.samplers.indexOf(name) === -1) {
  47239. this._options.samplers.push(name);
  47240. }
  47241. this._textures[name] = texture;
  47242. return this;
  47243. };
  47244. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47245. if (this._options.samplers.indexOf(name) === -1) {
  47246. this._options.samplers.push(name);
  47247. }
  47248. this._checkUniform(name);
  47249. this._textureArrays[name] = textures;
  47250. return this;
  47251. };
  47252. ShaderMaterial.prototype.setFloat = function (name, value) {
  47253. this._checkUniform(name);
  47254. this._floats[name] = value;
  47255. return this;
  47256. };
  47257. ShaderMaterial.prototype.setFloats = function (name, value) {
  47258. this._checkUniform(name);
  47259. this._floatsArrays[name] = value;
  47260. return this;
  47261. };
  47262. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47263. this._checkUniform(name);
  47264. this._colors3[name] = value;
  47265. return this;
  47266. };
  47267. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47268. this._checkUniform(name);
  47269. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47270. color.toArray(arr, arr.length);
  47271. return arr;
  47272. }, []);
  47273. return this;
  47274. };
  47275. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47276. this._checkUniform(name);
  47277. this._colors4[name] = value;
  47278. return this;
  47279. };
  47280. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47281. this._checkUniform(name);
  47282. this._vectors2[name] = value;
  47283. return this;
  47284. };
  47285. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47286. this._checkUniform(name);
  47287. this._vectors3[name] = value;
  47288. return this;
  47289. };
  47290. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47291. this._checkUniform(name);
  47292. this._vectors4[name] = value;
  47293. return this;
  47294. };
  47295. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47296. this._checkUniform(name);
  47297. this._matrices[name] = value;
  47298. return this;
  47299. };
  47300. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47301. this._checkUniform(name);
  47302. this._matrices3x3[name] = value;
  47303. return this;
  47304. };
  47305. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47306. this._checkUniform(name);
  47307. this._matrices2x2[name] = value;
  47308. return this;
  47309. };
  47310. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47311. this._checkUniform(name);
  47312. this._vectors2Arrays[name] = value;
  47313. return this;
  47314. };
  47315. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47316. this._checkUniform(name);
  47317. this._vectors3Arrays[name] = value;
  47318. return this;
  47319. };
  47320. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47321. if (!mesh) {
  47322. return true;
  47323. }
  47324. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47325. return false;
  47326. }
  47327. return false;
  47328. };
  47329. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47330. var scene = this.getScene();
  47331. var engine = scene.getEngine();
  47332. if (!this.checkReadyOnEveryCall) {
  47333. if (this._renderId === scene.getRenderId()) {
  47334. if (this._checkCache(scene, mesh, useInstances)) {
  47335. return true;
  47336. }
  47337. }
  47338. }
  47339. // Instances
  47340. var defines = [];
  47341. var attribs = [];
  47342. var fallbacks = new BABYLON.EffectFallbacks();
  47343. if (useInstances) {
  47344. defines.push("#define INSTANCES");
  47345. }
  47346. for (var index = 0; index < this._options.defines.length; index++) {
  47347. defines.push(this._options.defines[index]);
  47348. }
  47349. for (var index = 0; index < this._options.attributes.length; index++) {
  47350. attribs.push(this._options.attributes[index]);
  47351. }
  47352. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47353. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47354. defines.push("#define VERTEXCOLOR");
  47355. }
  47356. // Bones
  47357. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47358. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47359. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47360. if (mesh.numBoneInfluencers > 4) {
  47361. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47362. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47363. }
  47364. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47365. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47366. fallbacks.addCPUSkinningFallback(0, mesh);
  47367. if (this._options.uniforms.indexOf("mBones") === -1) {
  47368. this._options.uniforms.push("mBones");
  47369. }
  47370. }
  47371. else {
  47372. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47373. }
  47374. // Textures
  47375. for (var name in this._textures) {
  47376. if (!this._textures[name].isReady()) {
  47377. return false;
  47378. }
  47379. }
  47380. // Alpha test
  47381. if (engine.getAlphaTesting()) {
  47382. defines.push("#define ALPHATEST");
  47383. }
  47384. var previousEffect = this._effect;
  47385. var join = defines.join("\n");
  47386. this._effect = engine.createEffect(this._shaderPath, {
  47387. attributes: attribs,
  47388. uniformsNames: this._options.uniforms,
  47389. uniformBuffersNames: this._options.uniformBuffers,
  47390. samplers: this._options.samplers,
  47391. defines: join,
  47392. fallbacks: fallbacks,
  47393. onCompiled: this.onCompiled,
  47394. onError: this.onError
  47395. }, engine);
  47396. if (!this._effect.isReady()) {
  47397. return false;
  47398. }
  47399. if (previousEffect !== this._effect) {
  47400. scene.resetCachedMaterial();
  47401. }
  47402. this._renderId = scene.getRenderId();
  47403. return true;
  47404. };
  47405. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47406. var scene = this.getScene();
  47407. if (!this._effect) {
  47408. return;
  47409. }
  47410. if (this._options.uniforms.indexOf("world") !== -1) {
  47411. this._effect.setMatrix("world", world);
  47412. }
  47413. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47414. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47415. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47416. }
  47417. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47418. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47419. }
  47420. };
  47421. ShaderMaterial.prototype.bind = function (world, mesh) {
  47422. // Std values
  47423. this.bindOnlyWorldMatrix(world);
  47424. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47425. if (this._options.uniforms.indexOf("view") !== -1) {
  47426. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47427. }
  47428. if (this._options.uniforms.indexOf("projection") !== -1) {
  47429. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47430. }
  47431. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47432. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47433. }
  47434. // Bones
  47435. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47436. var name;
  47437. // Texture
  47438. for (name in this._textures) {
  47439. this._effect.setTexture(name, this._textures[name]);
  47440. }
  47441. // Texture arrays
  47442. for (name in this._textureArrays) {
  47443. this._effect.setTextureArray(name, this._textureArrays[name]);
  47444. }
  47445. // Float
  47446. for (name in this._floats) {
  47447. this._effect.setFloat(name, this._floats[name]);
  47448. }
  47449. // Float s
  47450. for (name in this._floatsArrays) {
  47451. this._effect.setArray(name, this._floatsArrays[name]);
  47452. }
  47453. // Color3
  47454. for (name in this._colors3) {
  47455. this._effect.setColor3(name, this._colors3[name]);
  47456. }
  47457. for (name in this._colors3Arrays) {
  47458. this._effect.setArray3(name, this._colors3Arrays[name]);
  47459. }
  47460. // Color4
  47461. for (name in this._colors4) {
  47462. var color = this._colors4[name];
  47463. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47464. }
  47465. // Vector2
  47466. for (name in this._vectors2) {
  47467. this._effect.setVector2(name, this._vectors2[name]);
  47468. }
  47469. // Vector3
  47470. for (name in this._vectors3) {
  47471. this._effect.setVector3(name, this._vectors3[name]);
  47472. }
  47473. // Vector4
  47474. for (name in this._vectors4) {
  47475. this._effect.setVector4(name, this._vectors4[name]);
  47476. }
  47477. // Matrix
  47478. for (name in this._matrices) {
  47479. this._effect.setMatrix(name, this._matrices[name]);
  47480. }
  47481. // Matrix 3x3
  47482. for (name in this._matrices3x3) {
  47483. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47484. }
  47485. // Matrix 2x2
  47486. for (name in this._matrices2x2) {
  47487. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47488. }
  47489. // Vector2Array
  47490. for (name in this._vectors2Arrays) {
  47491. this._effect.setArray2(name, this._vectors2Arrays[name]);
  47492. }
  47493. // Vector3Array
  47494. for (name in this._vectors3Arrays) {
  47495. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47496. }
  47497. }
  47498. this._afterBind(mesh);
  47499. };
  47500. ShaderMaterial.prototype.getActiveTextures = function () {
  47501. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47502. for (var name in this._textures) {
  47503. activeTextures.push(this._textures[name]);
  47504. }
  47505. for (var name in this._textureArrays) {
  47506. var array = this._textureArrays[name];
  47507. for (var index = 0; index < array.length; index++) {
  47508. activeTextures.push(array[index]);
  47509. }
  47510. }
  47511. return activeTextures;
  47512. };
  47513. ShaderMaterial.prototype.hasTexture = function (texture) {
  47514. if (_super.prototype.hasTexture.call(this, texture)) {
  47515. return true;
  47516. }
  47517. for (var name in this._textures) {
  47518. if (this._textures[name] === texture) {
  47519. return true;
  47520. }
  47521. }
  47522. for (var name in this._textureArrays) {
  47523. var array = this._textureArrays[name];
  47524. for (var index = 0; index < array.length; index++) {
  47525. if (array[index] === texture) {
  47526. return true;
  47527. }
  47528. }
  47529. }
  47530. return false;
  47531. };
  47532. ShaderMaterial.prototype.clone = function (name) {
  47533. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47534. return newShaderMaterial;
  47535. };
  47536. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47537. if (forceDisposeTextures) {
  47538. var name;
  47539. for (name in this._textures) {
  47540. this._textures[name].dispose();
  47541. }
  47542. for (name in this._textureArrays) {
  47543. var array = this._textureArrays[name];
  47544. for (var index = 0; index < array.length; index++) {
  47545. array[index].dispose();
  47546. }
  47547. }
  47548. }
  47549. this._textures = {};
  47550. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47551. };
  47552. ShaderMaterial.prototype.serialize = function () {
  47553. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47554. serializationObject.customType = "BABYLON.ShaderMaterial";
  47555. serializationObject.options = this._options;
  47556. serializationObject.shaderPath = this._shaderPath;
  47557. var name;
  47558. // Texture
  47559. serializationObject.textures = {};
  47560. for (name in this._textures) {
  47561. serializationObject.textures[name] = this._textures[name].serialize();
  47562. }
  47563. // Texture arrays
  47564. serializationObject.textureArrays = {};
  47565. for (name in this._textureArrays) {
  47566. serializationObject.textureArrays[name] = [];
  47567. var array = this._textureArrays[name];
  47568. for (var index = 0; index < array.length; index++) {
  47569. serializationObject.textureArrays[name].push(array[index].serialize());
  47570. }
  47571. }
  47572. // Float
  47573. serializationObject.floats = {};
  47574. for (name in this._floats) {
  47575. serializationObject.floats[name] = this._floats[name];
  47576. }
  47577. // Float s
  47578. serializationObject.FloatArrays = {};
  47579. for (name in this._floatsArrays) {
  47580. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47581. }
  47582. // Color3
  47583. serializationObject.colors3 = {};
  47584. for (name in this._colors3) {
  47585. serializationObject.colors3[name] = this._colors3[name].asArray();
  47586. }
  47587. // Color3 array
  47588. serializationObject.colors3Arrays = {};
  47589. for (name in this._colors3Arrays) {
  47590. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47591. }
  47592. // Color4
  47593. serializationObject.colors4 = {};
  47594. for (name in this._colors4) {
  47595. serializationObject.colors4[name] = this._colors4[name].asArray();
  47596. }
  47597. // Vector2
  47598. serializationObject.vectors2 = {};
  47599. for (name in this._vectors2) {
  47600. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47601. }
  47602. // Vector3
  47603. serializationObject.vectors3 = {};
  47604. for (name in this._vectors3) {
  47605. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47606. }
  47607. // Vector4
  47608. serializationObject.vectors4 = {};
  47609. for (name in this._vectors4) {
  47610. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47611. }
  47612. // Matrix
  47613. serializationObject.matrices = {};
  47614. for (name in this._matrices) {
  47615. serializationObject.matrices[name] = this._matrices[name].asArray();
  47616. }
  47617. // Matrix 3x3
  47618. serializationObject.matrices3x3 = {};
  47619. for (name in this._matrices3x3) {
  47620. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47621. }
  47622. // Matrix 2x2
  47623. serializationObject.matrices2x2 = {};
  47624. for (name in this._matrices2x2) {
  47625. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47626. }
  47627. // Vector2Array
  47628. serializationObject.vectors2Arrays = {};
  47629. for (name in this._vectors2Arrays) {
  47630. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  47631. }
  47632. // Vector3Array
  47633. serializationObject.vectors3Arrays = {};
  47634. for (name in this._vectors3Arrays) {
  47635. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47636. }
  47637. return serializationObject;
  47638. };
  47639. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47640. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47641. var name;
  47642. // Texture
  47643. for (name in source.textures) {
  47644. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47645. }
  47646. // Texture arrays
  47647. for (name in source.textureArrays) {
  47648. var array = source.textureArrays[name];
  47649. var textureArray = new Array();
  47650. for (var index = 0; index < array.length; index++) {
  47651. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47652. }
  47653. material.setTextureArray(name, textureArray);
  47654. }
  47655. // Float
  47656. for (name in source.floats) {
  47657. material.setFloat(name, source.floats[name]);
  47658. }
  47659. // Float s
  47660. for (name in source.floatsArrays) {
  47661. material.setFloats(name, source.floatsArrays[name]);
  47662. }
  47663. // Color3
  47664. for (name in source.colors3) {
  47665. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47666. }
  47667. // Color3 arrays
  47668. for (name in source.colors3Arrays) {
  47669. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47670. if (i % 3 === 0) {
  47671. arr.push([num]);
  47672. }
  47673. else {
  47674. arr[arr.length - 1].push(num);
  47675. }
  47676. return arr;
  47677. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47678. material.setColor3Array(name, colors);
  47679. }
  47680. // Color4
  47681. for (name in source.colors4) {
  47682. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47683. }
  47684. // Vector2
  47685. for (name in source.vectors2) {
  47686. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47687. }
  47688. // Vector3
  47689. for (name in source.vectors3) {
  47690. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47691. }
  47692. // Vector4
  47693. for (name in source.vectors4) {
  47694. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47695. }
  47696. // Matrix
  47697. for (name in source.matrices) {
  47698. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47699. }
  47700. // Matrix 3x3
  47701. for (name in source.matrices3x3) {
  47702. material.setMatrix3x3(name, source.matrices3x3[name]);
  47703. }
  47704. // Matrix 2x2
  47705. for (name in source.matrices2x2) {
  47706. material.setMatrix2x2(name, source.matrices2x2[name]);
  47707. }
  47708. // Vector2Array
  47709. for (name in source.vectors2Arrays) {
  47710. material.setArray2(name, source.vectors2Arrays[name]);
  47711. }
  47712. // Vector3Array
  47713. for (name in source.vectors3Arrays) {
  47714. material.setArray3(name, source.vectors3Arrays[name]);
  47715. }
  47716. return material;
  47717. };
  47718. return ShaderMaterial;
  47719. }(BABYLON.Material));
  47720. BABYLON.ShaderMaterial = ShaderMaterial;
  47721. })(BABYLON || (BABYLON = {}));
  47722. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47723. var BABYLON;
  47724. (function (BABYLON) {
  47725. var MeshBuilder = /** @class */ (function () {
  47726. function MeshBuilder() {
  47727. }
  47728. MeshBuilder.updateSideOrientation = function (orientation) {
  47729. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47730. return BABYLON.Mesh.DOUBLESIDE;
  47731. }
  47732. if (orientation === undefined || orientation === null) {
  47733. return BABYLON.Mesh.FRONTSIDE;
  47734. }
  47735. return orientation;
  47736. };
  47737. /**
  47738. * Creates a box mesh.
  47739. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47740. * The parameter `size` sets the size (float) of each box side (default 1).
  47741. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47742. * 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).
  47743. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47745. * 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).
  47746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47748. */
  47749. MeshBuilder.CreateBox = function (name, options, scene) {
  47750. if (scene === void 0) { scene = null; }
  47751. var box = new BABYLON.Mesh(name, scene);
  47752. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47753. box._originalBuilderSideOrientation = options.sideOrientation;
  47754. var vertexData = BABYLON.VertexData.CreateBox(options);
  47755. vertexData.applyToMesh(box, options.updatable);
  47756. return box;
  47757. };
  47758. /**
  47759. * Creates a sphere mesh.
  47760. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47761. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47762. * 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`).
  47763. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47764. * 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
  47765. * 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).
  47766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47767. * 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).
  47768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47770. */
  47771. MeshBuilder.CreateSphere = function (name, options, scene) {
  47772. var sphere = new BABYLON.Mesh(name, scene);
  47773. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47774. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47775. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47776. vertexData.applyToMesh(sphere, options.updatable);
  47777. return sphere;
  47778. };
  47779. /**
  47780. * Creates a plane polygonal mesh. By default, this is a disc.
  47781. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47782. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47783. * 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.
  47784. * 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
  47785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47786. * 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).
  47787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47789. */
  47790. MeshBuilder.CreateDisc = function (name, options, scene) {
  47791. if (scene === void 0) { scene = null; }
  47792. var disc = new BABYLON.Mesh(name, scene);
  47793. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47794. disc._originalBuilderSideOrientation = options.sideOrientation;
  47795. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47796. vertexData.applyToMesh(disc, options.updatable);
  47797. return disc;
  47798. };
  47799. /**
  47800. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47802. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47803. * 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`).
  47804. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47805. * 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.
  47806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47807. * 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).
  47808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47810. */
  47811. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47812. var sphere = new BABYLON.Mesh(name, scene);
  47813. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47814. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47815. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47816. vertexData.applyToMesh(sphere, options.updatable);
  47817. return sphere;
  47818. };
  47819. ;
  47820. /**
  47821. * Creates a ribbon mesh.
  47822. * 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.
  47823. *
  47824. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47825. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47826. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47827. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47828. * 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.
  47829. * 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.
  47830. * 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
  47831. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47832. * 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).
  47833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47834. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47835. * 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.
  47836. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47837. * 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
  47838. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47839. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47841. */
  47842. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47843. if (scene === void 0) { scene = null; }
  47844. var pathArray = options.pathArray;
  47845. var closeArray = options.closeArray;
  47846. var closePath = options.closePath;
  47847. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47848. var instance = options.instance;
  47849. var updatable = options.updatable;
  47850. if (instance) {
  47851. // positionFunction : ribbon case
  47852. // only pathArray and sideOrientation parameters are taken into account for positions update
  47853. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47854. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47855. var positionFunction = function (positions) {
  47856. var minlg = pathArray[0].length;
  47857. var i = 0;
  47858. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47859. for (var si = 1; si <= ns; si++) {
  47860. for (var p = 0; p < pathArray.length; p++) {
  47861. var path = pathArray[p];
  47862. var l = path.length;
  47863. minlg = (minlg < l) ? minlg : l;
  47864. var j = 0;
  47865. while (j < minlg) {
  47866. positions[i] = path[j].x;
  47867. positions[i + 1] = path[j].y;
  47868. positions[i + 2] = path[j].z;
  47869. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47870. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47871. }
  47872. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47873. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47874. }
  47875. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47876. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47877. }
  47878. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47879. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47880. }
  47881. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47882. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47883. }
  47884. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47885. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47886. }
  47887. j++;
  47888. i += 3;
  47889. }
  47890. if (instance._closePath) {
  47891. positions[i] = path[0].x;
  47892. positions[i + 1] = path[0].y;
  47893. positions[i + 2] = path[0].z;
  47894. i += 3;
  47895. }
  47896. }
  47897. }
  47898. };
  47899. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47900. positionFunction(positions);
  47901. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47902. instance._boundingInfo.update(instance._worldMatrix);
  47903. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47904. if (options.colors) {
  47905. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47906. for (var c = 0; c < options.colors.length; c++) {
  47907. colors[c * 4] = options.colors[c].r;
  47908. colors[c * 4 + 1] = options.colors[c].g;
  47909. colors[c * 4 + 2] = options.colors[c].b;
  47910. colors[c * 4 + 3] = options.colors[c].a;
  47911. }
  47912. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47913. }
  47914. if (options.uvs) {
  47915. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47916. for (var i = 0; i < options.uvs.length; i++) {
  47917. uvs[i * 2] = options.uvs[i].x;
  47918. uvs[i * 2 + 1] = options.uvs[i].y;
  47919. }
  47920. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47921. }
  47922. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47923. var indices = instance.getIndices();
  47924. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47925. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47926. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47927. if (instance._closePath) {
  47928. var indexFirst = 0;
  47929. var indexLast = 0;
  47930. for (var p = 0; p < pathArray.length; p++) {
  47931. indexFirst = instance._idx[p] * 3;
  47932. if (p + 1 < pathArray.length) {
  47933. indexLast = (instance._idx[p + 1] - 1) * 3;
  47934. }
  47935. else {
  47936. indexLast = normals.length - 3;
  47937. }
  47938. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47939. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47940. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47941. normals[indexLast] = normals[indexFirst];
  47942. normals[indexLast + 1] = normals[indexFirst + 1];
  47943. normals[indexLast + 2] = normals[indexFirst + 2];
  47944. }
  47945. }
  47946. if (!(instance.areNormalsFrozen)) {
  47947. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47948. }
  47949. }
  47950. return instance;
  47951. }
  47952. else {
  47953. var ribbon = new BABYLON.Mesh(name, scene);
  47954. ribbon._originalBuilderSideOrientation = sideOrientation;
  47955. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47956. if (closePath) {
  47957. ribbon._idx = vertexData._idx;
  47958. }
  47959. ribbon._closePath = closePath;
  47960. ribbon._closeArray = closeArray;
  47961. vertexData.applyToMesh(ribbon, updatable);
  47962. return ribbon;
  47963. }
  47964. };
  47965. /**
  47966. * Creates a cylinder or a cone mesh.
  47967. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47968. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47969. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47970. * 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.
  47971. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47972. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47973. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47974. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47975. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47976. * 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).
  47977. * 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
  47978. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47979. * 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
  47980. * 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.
  47981. * If `enclose` is false, a ring surface is one element.
  47982. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47983. * 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
  47984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47985. * 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).
  47986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47988. */
  47989. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47990. var cylinder = new BABYLON.Mesh(name, scene);
  47991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47992. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47993. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47994. vertexData.applyToMesh(cylinder, options.updatable);
  47995. return cylinder;
  47996. };
  47997. /**
  47998. * Creates a torus mesh.
  47999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48000. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48001. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48002. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48003. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48004. * 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).
  48005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48007. */
  48008. MeshBuilder.CreateTorus = function (name, options, scene) {
  48009. var torus = new BABYLON.Mesh(name, scene);
  48010. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48011. torus._originalBuilderSideOrientation = options.sideOrientation;
  48012. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48013. vertexData.applyToMesh(torus, options.updatable);
  48014. return torus;
  48015. };
  48016. /**
  48017. * Creates a torus knot mesh.
  48018. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48019. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48020. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48021. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48022. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48024. * 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).
  48025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48027. */
  48028. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48029. var torusKnot = new BABYLON.Mesh(name, scene);
  48030. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48031. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48032. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48033. vertexData.applyToMesh(torusKnot, options.updatable);
  48034. return torusKnot;
  48035. };
  48036. /**
  48037. * Creates a line system mesh.
  48038. * A line system is a pool of many lines gathered in a single mesh.
  48039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48040. * 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.
  48041. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48042. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48043. * 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
  48044. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48045. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48046. * 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
  48047. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48049. */
  48050. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48051. var instance = options.instance;
  48052. var lines = options.lines;
  48053. var colors = options.colors;
  48054. if (instance) {
  48055. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48056. var vertexColor;
  48057. var lineColors;
  48058. if (colors) {
  48059. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48060. }
  48061. var i = 0;
  48062. var c = 0;
  48063. for (var l = 0; l < lines.length; l++) {
  48064. var points = lines[l];
  48065. for (var p = 0; p < points.length; p++) {
  48066. positions[i] = points[p].x;
  48067. positions[i + 1] = points[p].y;
  48068. positions[i + 2] = points[p].z;
  48069. if (colors && vertexColor) {
  48070. lineColors = colors[l];
  48071. vertexColor[c] = lineColors[p].r;
  48072. vertexColor[c + 1] = lineColors[p].g;
  48073. vertexColor[c + 2] = lineColors[p].b;
  48074. vertexColor[c + 3] = lineColors[p].a;
  48075. c += 4;
  48076. }
  48077. i += 3;
  48078. }
  48079. }
  48080. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48081. if (colors && vertexColor) {
  48082. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48083. }
  48084. return instance;
  48085. }
  48086. // line system creation
  48087. var useVertexColor = (colors) ? true : false;
  48088. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48089. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48090. vertexData.applyToMesh(lineSystem, options.updatable);
  48091. return lineSystem;
  48092. };
  48093. /**
  48094. * Creates a line mesh.
  48095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48096. * 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.
  48097. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48098. * The parameter `points` is an array successive Vector3.
  48099. * 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
  48100. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48101. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48102. * When updating an instance, remember that only point positions can change, not the number of points.
  48103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48104. */
  48105. MeshBuilder.CreateLines = function (name, options, scene) {
  48106. if (scene === void 0) { scene = null; }
  48107. var colors = (options.colors) ? [options.colors] : null;
  48108. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48109. return lines;
  48110. };
  48111. /**
  48112. * Creates a dashed line mesh.
  48113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48114. * 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.
  48115. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48116. * The parameter `points` is an array successive Vector3.
  48117. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48118. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48119. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48120. * 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
  48121. * When updating an instance, remember that only point positions can change, not the number of points.
  48122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48123. */
  48124. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48125. if (scene === void 0) { scene = null; }
  48126. var points = options.points;
  48127. var instance = options.instance;
  48128. var gapSize = options.gapSize || 1;
  48129. var dashSize = options.dashSize || 3;
  48130. if (instance) {
  48131. var positionFunction = function (positions) {
  48132. var curvect = BABYLON.Vector3.Zero();
  48133. var nbSeg = positions.length / 6;
  48134. var lg = 0;
  48135. var nb = 0;
  48136. var shft = 0;
  48137. var dashshft = 0;
  48138. var curshft = 0;
  48139. var p = 0;
  48140. var i = 0;
  48141. var j = 0;
  48142. for (i = 0; i < points.length - 1; i++) {
  48143. points[i + 1].subtractToRef(points[i], curvect);
  48144. lg += curvect.length();
  48145. }
  48146. shft = lg / nbSeg;
  48147. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48148. for (i = 0; i < points.length - 1; i++) {
  48149. points[i + 1].subtractToRef(points[i], curvect);
  48150. nb = Math.floor(curvect.length() / shft);
  48151. curvect.normalize();
  48152. j = 0;
  48153. while (j < nb && p < positions.length) {
  48154. curshft = shft * j;
  48155. positions[p] = points[i].x + curshft * curvect.x;
  48156. positions[p + 1] = points[i].y + curshft * curvect.y;
  48157. positions[p + 2] = points[i].z + curshft * curvect.z;
  48158. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48159. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48160. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48161. p += 6;
  48162. j++;
  48163. }
  48164. }
  48165. while (p < positions.length) {
  48166. positions[p] = points[i].x;
  48167. positions[p + 1] = points[i].y;
  48168. positions[p + 2] = points[i].z;
  48169. p += 3;
  48170. }
  48171. };
  48172. instance.updateMeshPositions(positionFunction, false);
  48173. return instance;
  48174. }
  48175. // dashed lines creation
  48176. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48177. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48178. vertexData.applyToMesh(dashedLines, options.updatable);
  48179. dashedLines.dashSize = dashSize;
  48180. dashedLines.gapSize = gapSize;
  48181. return dashedLines;
  48182. };
  48183. /**
  48184. * Creates an extruded shape mesh.
  48185. * 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.
  48186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48187. *
  48188. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48189. * 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
  48190. * extruded along the Z axis.
  48191. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48192. * 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.
  48193. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48194. * 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
  48195. * 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
  48196. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48198. * 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).
  48199. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48200. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48202. */
  48203. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48204. if (scene === void 0) { scene = null; }
  48205. var path = options.path;
  48206. var shape = options.shape;
  48207. var scale = options.scale || 1;
  48208. var rotation = options.rotation || 0;
  48209. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48210. var updatable = options.updatable;
  48211. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48212. var instance = options.instance || null;
  48213. var invertUV = options.invertUV || false;
  48214. 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);
  48215. };
  48216. /**
  48217. * Creates an custom extruded shape mesh.
  48218. * 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.
  48219. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48220. *
  48221. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48222. * 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
  48223. * extruded along the Z axis.
  48224. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48225. * 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
  48226. * and the distance of this point from the begining of the path :
  48227. * ```javascript
  48228. * var rotationFunction = function(i, distance) {
  48229. * // do things
  48230. * return rotationValue; }
  48231. * ```
  48232. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48233. * 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
  48234. * and the distance of this point from the begining of the path :
  48235. * ```javascript
  48236. * var scaleFunction = function(i, distance) {
  48237. * // do things
  48238. * return scaleValue;}
  48239. * ```
  48240. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48241. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48242. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48243. * 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
  48244. * 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
  48245. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48247. * 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).
  48248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48249. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48251. */
  48252. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48253. var path = options.path;
  48254. var shape = options.shape;
  48255. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48256. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48257. var ribbonCloseArray = options.ribbonCloseArray || false;
  48258. var ribbonClosePath = options.ribbonClosePath || false;
  48259. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48260. var updatable = options.updatable;
  48261. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48262. var instance = options.instance;
  48263. var invertUV = options.invertUV || false;
  48264. 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);
  48265. };
  48266. /**
  48267. * Creates lathe mesh.
  48268. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48269. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48270. *
  48271. * 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
  48272. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48273. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48274. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48275. * 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.
  48276. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48277. * 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
  48278. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48279. * 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).
  48280. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48281. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48282. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48283. */
  48284. MeshBuilder.CreateLathe = function (name, options, scene) {
  48285. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48286. var closed = (options.closed === undefined) ? true : options.closed;
  48287. var shape = options.shape;
  48288. var radius = options.radius || 1;
  48289. var tessellation = options.tessellation || 64;
  48290. var updatable = options.updatable;
  48291. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48292. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48293. var pi2 = Math.PI * 2;
  48294. var paths = new Array();
  48295. var invertUV = options.invertUV || false;
  48296. var i = 0;
  48297. var p = 0;
  48298. var step = pi2 / tessellation * arc;
  48299. var rotated;
  48300. var path = new Array();
  48301. ;
  48302. for (i = 0; i <= tessellation; i++) {
  48303. var path = [];
  48304. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48305. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48306. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48307. }
  48308. for (p = 0; p < shape.length; p++) {
  48309. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48310. path.push(rotated);
  48311. }
  48312. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48313. 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));
  48314. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48315. }
  48316. paths.push(path);
  48317. }
  48318. // lathe ribbon
  48319. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48320. return lathe;
  48321. };
  48322. /**
  48323. * Creates a plane mesh.
  48324. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48325. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48326. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48327. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48329. * 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).
  48330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48332. */
  48333. MeshBuilder.CreatePlane = function (name, options, scene) {
  48334. var plane = new BABYLON.Mesh(name, scene);
  48335. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48336. plane._originalBuilderSideOrientation = options.sideOrientation;
  48337. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48338. vertexData.applyToMesh(plane, options.updatable);
  48339. if (options.sourcePlane) {
  48340. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48341. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48342. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48343. plane.rotate(vectorProduct, product);
  48344. }
  48345. return plane;
  48346. };
  48347. /**
  48348. * Creates a ground mesh.
  48349. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48350. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48351. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48353. */
  48354. MeshBuilder.CreateGround = function (name, options, scene) {
  48355. var ground = new BABYLON.GroundMesh(name, scene);
  48356. ground._setReady(false);
  48357. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48358. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48359. ground._width = options.width || 1;
  48360. ground._height = options.height || 1;
  48361. ground._maxX = ground._width / 2;
  48362. ground._maxZ = ground._height / 2;
  48363. ground._minX = -ground._maxX;
  48364. ground._minZ = -ground._maxZ;
  48365. var vertexData = BABYLON.VertexData.CreateGround(options);
  48366. vertexData.applyToMesh(ground, options.updatable);
  48367. ground._setReady(true);
  48368. return ground;
  48369. };
  48370. /**
  48371. * Creates a tiled ground mesh.
  48372. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48373. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48374. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48375. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48376. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48377. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48378. * numbers of subdivisions on the ground width and height of each tile.
  48379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48380. */
  48381. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48382. var tiledGround = new BABYLON.Mesh(name, scene);
  48383. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48384. vertexData.applyToMesh(tiledGround, options.updatable);
  48385. return tiledGround;
  48386. };
  48387. /**
  48388. * Creates a ground mesh from a height map.
  48389. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48390. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48391. * The parameter `url` sets the URL of the height map image resource.
  48392. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48393. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48394. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48395. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48396. * 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.
  48397. * 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).
  48398. * This function is passed the newly built mesh :
  48399. * ```javascript
  48400. * function(mesh) { // do things
  48401. * return; }
  48402. * ```
  48403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48404. */
  48405. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48406. var width = options.width || 10.0;
  48407. var height = options.height || 10.0;
  48408. var subdivisions = options.subdivisions || 1 | 0;
  48409. var minHeight = options.minHeight || 0.0;
  48410. var maxHeight = options.maxHeight || 1.0;
  48411. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48412. var updatable = options.updatable;
  48413. var onReady = options.onReady;
  48414. var ground = new BABYLON.GroundMesh(name, scene);
  48415. ground._subdivisionsX = subdivisions;
  48416. ground._subdivisionsY = subdivisions;
  48417. ground._width = width;
  48418. ground._height = height;
  48419. ground._maxX = ground._width / 2.0;
  48420. ground._maxZ = ground._height / 2.0;
  48421. ground._minX = -ground._maxX;
  48422. ground._minZ = -ground._maxZ;
  48423. ground._setReady(false);
  48424. var onload = function (img) {
  48425. // Getting height map data
  48426. var canvas = document.createElement("canvas");
  48427. var context = canvas.getContext("2d");
  48428. if (!context) {
  48429. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48430. }
  48431. var bufferWidth = img.width;
  48432. var bufferHeight = img.height;
  48433. canvas.width = bufferWidth;
  48434. canvas.height = bufferHeight;
  48435. context.drawImage(img, 0, 0);
  48436. // Create VertexData from map data
  48437. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48438. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48439. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48440. width: width, height: height,
  48441. subdivisions: subdivisions,
  48442. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48443. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48444. });
  48445. vertexData.applyToMesh(ground, updatable);
  48446. ground._setReady(true);
  48447. //execute ready callback, if set
  48448. if (onReady) {
  48449. onReady(ground);
  48450. }
  48451. };
  48452. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48453. return ground;
  48454. };
  48455. /**
  48456. * Creates a polygon mesh.
  48457. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48458. * 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.
  48459. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48461. * 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).
  48462. * Remember you can only change the shape positions, not their number when updating a polygon.
  48463. */
  48464. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48466. var shape = options.shape;
  48467. var holes = options.holes || [];
  48468. var depth = options.depth || 0;
  48469. var contours = [];
  48470. var hole = [];
  48471. for (var i = 0; i < shape.length; i++) {
  48472. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48473. }
  48474. var epsilon = 0.00000001;
  48475. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48476. contours.pop();
  48477. }
  48478. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48479. for (var hNb = 0; hNb < holes.length; hNb++) {
  48480. hole = [];
  48481. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48482. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48483. }
  48484. polygonTriangulation.addHole(hole);
  48485. }
  48486. var polygon = polygonTriangulation.build(options.updatable, depth);
  48487. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48488. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48489. vertexData.applyToMesh(polygon, options.updatable);
  48490. return polygon;
  48491. };
  48492. ;
  48493. /**
  48494. * Creates an extruded polygon mesh, with depth in the Y direction.
  48495. * 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).
  48496. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48497. */
  48498. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48499. return MeshBuilder.CreatePolygon(name, options, scene);
  48500. };
  48501. ;
  48502. /**
  48503. * Creates a tube mesh.
  48504. * 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.
  48505. *
  48506. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48507. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48508. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48509. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48510. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48511. * 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.
  48512. * It must return a radius value (positive float) :
  48513. * ```javascript
  48514. * var radiusFunction = function(i, distance) {
  48515. * // do things
  48516. * return radius; }
  48517. * ```
  48518. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48519. * 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
  48520. * 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
  48521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48522. * 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).
  48523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48524. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48526. */
  48527. MeshBuilder.CreateTube = function (name, options, scene) {
  48528. var path = options.path;
  48529. var instance = options.instance;
  48530. var radius = 1.0;
  48531. if (instance) {
  48532. radius = instance.radius;
  48533. }
  48534. if (options.radius !== undefined) {
  48535. radius = options.radius;
  48536. }
  48537. ;
  48538. var tessellation = options.tessellation || 64 | 0;
  48539. var radiusFunction = options.radiusFunction || null;
  48540. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48541. var invertUV = options.invertUV || false;
  48542. var updatable = options.updatable;
  48543. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48544. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48545. // tube geometry
  48546. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48547. var tangents = path3D.getTangents();
  48548. var normals = path3D.getNormals();
  48549. var distances = path3D.getDistances();
  48550. var pi2 = Math.PI * 2;
  48551. var step = pi2 / tessellation * arc;
  48552. var returnRadius = function () { return radius; };
  48553. var radiusFunctionFinal = radiusFunction || returnRadius;
  48554. var circlePath;
  48555. var rad;
  48556. var normal;
  48557. var rotated;
  48558. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48559. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48560. for (var i = 0; i < path.length; i++) {
  48561. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48562. circlePath = Array(); // current circle array
  48563. normal = normals[i]; // current normal
  48564. for (var t = 0; t < tessellation; t++) {
  48565. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48566. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48567. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48568. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48569. circlePath[t] = rotated;
  48570. }
  48571. circlePaths[index] = circlePath;
  48572. index++;
  48573. }
  48574. // cap
  48575. var capPath = function (nbPoints, pathIndex) {
  48576. var pointCap = Array();
  48577. for (var i = 0; i < nbPoints; i++) {
  48578. pointCap.push(path[pathIndex]);
  48579. }
  48580. return pointCap;
  48581. };
  48582. switch (cap) {
  48583. case BABYLON.Mesh.NO_CAP:
  48584. break;
  48585. case BABYLON.Mesh.CAP_START:
  48586. circlePaths[0] = capPath(tessellation, 0);
  48587. circlePaths[1] = circlePaths[2].slice(0);
  48588. break;
  48589. case BABYLON.Mesh.CAP_END:
  48590. circlePaths[index] = circlePaths[index - 1].slice(0);
  48591. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48592. break;
  48593. case BABYLON.Mesh.CAP_ALL:
  48594. circlePaths[0] = capPath(tessellation, 0);
  48595. circlePaths[1] = circlePaths[2].slice(0);
  48596. circlePaths[index] = circlePaths[index - 1].slice(0);
  48597. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48598. break;
  48599. default:
  48600. break;
  48601. }
  48602. return circlePaths;
  48603. };
  48604. var path3D;
  48605. var pathArray;
  48606. if (instance) {
  48607. var arc = options.arc || instance.arc;
  48608. path3D = (instance.path3D).update(path);
  48609. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48610. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48611. instance.path3D = path3D;
  48612. instance.pathArray = pathArray;
  48613. instance.arc = arc;
  48614. instance.radius = radius;
  48615. return instance;
  48616. }
  48617. // tube creation
  48618. path3D = new BABYLON.Path3D(path);
  48619. var newPathArray = new Array();
  48620. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48621. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48622. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48623. tube.pathArray = pathArray;
  48624. tube.path3D = path3D;
  48625. tube.tessellation = tessellation;
  48626. tube.cap = cap;
  48627. tube.arc = options.arc;
  48628. tube.radius = radius;
  48629. return tube;
  48630. };
  48631. /**
  48632. * Creates a polyhedron mesh.
  48633. *
  48634. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48635. * 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
  48636. * to choose the wanted type.
  48637. * The parameter `size` (positive float, default 1) sets the polygon size.
  48638. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48639. * 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`.
  48640. * 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
  48641. * 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)`).
  48642. * 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
  48643. * 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.
  48644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48645. * 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).
  48646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48648. */
  48649. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48650. var polyhedron = new BABYLON.Mesh(name, scene);
  48651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48652. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48653. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48654. vertexData.applyToMesh(polyhedron, options.updatable);
  48655. return polyhedron;
  48656. };
  48657. /**
  48658. * Creates a decal mesh.
  48659. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48660. * 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.
  48661. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48662. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48663. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48664. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48665. */
  48666. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48667. var indices = sourceMesh.getIndices();
  48668. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48669. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48670. var position = options.position || BABYLON.Vector3.Zero();
  48671. var normal = options.normal || BABYLON.Vector3.Up();
  48672. var size = options.size || BABYLON.Vector3.One();
  48673. var angle = options.angle || 0;
  48674. // Getting correct rotation
  48675. if (!normal) {
  48676. var target = new BABYLON.Vector3(0, 0, 1);
  48677. var camera = sourceMesh.getScene().activeCamera;
  48678. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48679. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48680. }
  48681. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48682. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48683. var pitch = Math.atan2(normal.y, len);
  48684. // Matrix
  48685. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48686. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48687. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48688. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48689. var vertexData = new BABYLON.VertexData();
  48690. vertexData.indices = [];
  48691. vertexData.positions = [];
  48692. vertexData.normals = [];
  48693. vertexData.uvs = [];
  48694. var currentVertexDataIndex = 0;
  48695. var extractDecalVector3 = function (indexId) {
  48696. var result = new BABYLON.PositionNormalVertex();
  48697. if (!indices || !positions || !normals) {
  48698. return result;
  48699. }
  48700. var vertexId = indices[indexId];
  48701. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48702. // Send vector to decal local world
  48703. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48704. // Get normal
  48705. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48706. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48707. return result;
  48708. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48709. var clip = function (vertices, axis) {
  48710. if (vertices.length === 0) {
  48711. return vertices;
  48712. }
  48713. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48714. var clipVertices = function (v0, v1) {
  48715. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48716. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48717. };
  48718. var result = new Array();
  48719. for (var index = 0; index < vertices.length; index += 3) {
  48720. var v1Out;
  48721. var v2Out;
  48722. var v3Out;
  48723. var total = 0;
  48724. var nV1 = null;
  48725. var nV2 = null;
  48726. var nV3 = null;
  48727. var nV4 = null;
  48728. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48729. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48730. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48731. v1Out = d1 > 0;
  48732. v2Out = d2 > 0;
  48733. v3Out = d3 > 0;
  48734. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48735. switch (total) {
  48736. case 0:
  48737. result.push(vertices[index]);
  48738. result.push(vertices[index + 1]);
  48739. result.push(vertices[index + 2]);
  48740. break;
  48741. case 1:
  48742. if (v1Out) {
  48743. nV1 = vertices[index + 1];
  48744. nV2 = vertices[index + 2];
  48745. nV3 = clipVertices(vertices[index], nV1);
  48746. nV4 = clipVertices(vertices[index], nV2);
  48747. }
  48748. if (v2Out) {
  48749. nV1 = vertices[index];
  48750. nV2 = vertices[index + 2];
  48751. nV3 = clipVertices(vertices[index + 1], nV1);
  48752. nV4 = clipVertices(vertices[index + 1], nV2);
  48753. result.push(nV3);
  48754. result.push(nV2.clone());
  48755. result.push(nV1.clone());
  48756. result.push(nV2.clone());
  48757. result.push(nV3.clone());
  48758. result.push(nV4);
  48759. break;
  48760. }
  48761. if (v3Out) {
  48762. nV1 = vertices[index];
  48763. nV2 = vertices[index + 1];
  48764. nV3 = clipVertices(vertices[index + 2], nV1);
  48765. nV4 = clipVertices(vertices[index + 2], nV2);
  48766. }
  48767. if (nV1 && nV2 && nV3 && nV4) {
  48768. result.push(nV1.clone());
  48769. result.push(nV2.clone());
  48770. result.push(nV3);
  48771. result.push(nV4);
  48772. result.push(nV3.clone());
  48773. result.push(nV2.clone());
  48774. }
  48775. break;
  48776. case 2:
  48777. if (!v1Out) {
  48778. nV1 = vertices[index].clone();
  48779. nV2 = clipVertices(nV1, vertices[index + 1]);
  48780. nV3 = clipVertices(nV1, vertices[index + 2]);
  48781. result.push(nV1);
  48782. result.push(nV2);
  48783. result.push(nV3);
  48784. }
  48785. if (!v2Out) {
  48786. nV1 = vertices[index + 1].clone();
  48787. nV2 = clipVertices(nV1, vertices[index + 2]);
  48788. nV3 = clipVertices(nV1, vertices[index]);
  48789. result.push(nV1);
  48790. result.push(nV2);
  48791. result.push(nV3);
  48792. }
  48793. if (!v3Out) {
  48794. nV1 = vertices[index + 2].clone();
  48795. nV2 = clipVertices(nV1, vertices[index]);
  48796. nV3 = clipVertices(nV1, vertices[index + 1]);
  48797. result.push(nV1);
  48798. result.push(nV2);
  48799. result.push(nV3);
  48800. }
  48801. break;
  48802. case 3:
  48803. break;
  48804. }
  48805. }
  48806. return result;
  48807. };
  48808. for (var index = 0; index < indices.length; index += 3) {
  48809. var faceVertices = new Array();
  48810. faceVertices.push(extractDecalVector3(index));
  48811. faceVertices.push(extractDecalVector3(index + 1));
  48812. faceVertices.push(extractDecalVector3(index + 2));
  48813. // Clip
  48814. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48815. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48816. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48817. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48818. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48820. if (faceVertices.length === 0) {
  48821. continue;
  48822. }
  48823. // Add UVs and get back to world
  48824. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48825. var vertex = faceVertices[vIndex];
  48826. //TODO check for Int32Array | Uint32Array | Uint16Array
  48827. vertexData.indices.push(currentVertexDataIndex);
  48828. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48829. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48830. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48831. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48832. currentVertexDataIndex++;
  48833. }
  48834. }
  48835. // Return mesh
  48836. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48837. vertexData.applyToMesh(decal);
  48838. decal.position = position.clone();
  48839. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48840. return decal;
  48841. };
  48842. // Privates
  48843. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48844. // extrusion geometry
  48845. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48846. var tangents = path3D.getTangents();
  48847. var normals = path3D.getNormals();
  48848. var binormals = path3D.getBinormals();
  48849. var distances = path3D.getDistances();
  48850. var angle = 0;
  48851. var returnScale = function () { return scale !== null ? scale : 1; };
  48852. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48853. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48854. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48855. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48856. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48857. for (var i = 0; i < curve.length; i++) {
  48858. var shapePath = new Array();
  48859. var angleStep = rotate(i, distances[i]);
  48860. var scaleRatio = scl(i, distances[i]);
  48861. for (var p = 0; p < shape.length; p++) {
  48862. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48863. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48864. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48865. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48866. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48867. shapePath[p] = rotated;
  48868. }
  48869. shapePaths[index] = shapePath;
  48870. angle += angleStep;
  48871. index++;
  48872. }
  48873. // cap
  48874. var capPath = function (shapePath) {
  48875. var pointCap = Array();
  48876. var barycenter = BABYLON.Vector3.Zero();
  48877. var i;
  48878. for (i = 0; i < shapePath.length; i++) {
  48879. barycenter.addInPlace(shapePath[i]);
  48880. }
  48881. barycenter.scaleInPlace(1.0 / shapePath.length);
  48882. for (i = 0; i < shapePath.length; i++) {
  48883. pointCap.push(barycenter);
  48884. }
  48885. return pointCap;
  48886. };
  48887. switch (cap) {
  48888. case BABYLON.Mesh.NO_CAP:
  48889. break;
  48890. case BABYLON.Mesh.CAP_START:
  48891. shapePaths[0] = capPath(shapePaths[2]);
  48892. shapePaths[1] = shapePaths[2];
  48893. break;
  48894. case BABYLON.Mesh.CAP_END:
  48895. shapePaths[index] = shapePaths[index - 1];
  48896. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48897. break;
  48898. case BABYLON.Mesh.CAP_ALL:
  48899. shapePaths[0] = capPath(shapePaths[2]);
  48900. shapePaths[1] = shapePaths[2];
  48901. shapePaths[index] = shapePaths[index - 1];
  48902. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48903. break;
  48904. default:
  48905. break;
  48906. }
  48907. return shapePaths;
  48908. };
  48909. var path3D;
  48910. var pathArray;
  48911. if (instance) {
  48912. path3D = (instance.path3D).update(curve);
  48913. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48914. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48915. return instance;
  48916. }
  48917. // extruded shape creation
  48918. path3D = new BABYLON.Path3D(curve);
  48919. var newShapePaths = new Array();
  48920. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48921. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48922. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48923. extrudedGeneric.pathArray = pathArray;
  48924. extrudedGeneric.path3D = path3D;
  48925. extrudedGeneric.cap = cap;
  48926. return extrudedGeneric;
  48927. };
  48928. return MeshBuilder;
  48929. }());
  48930. BABYLON.MeshBuilder = MeshBuilder;
  48931. })(BABYLON || (BABYLON = {}));
  48932. //# sourceMappingURL=babylon.meshBuilder.js.map
  48933. var BABYLON;
  48934. (function (BABYLON) {
  48935. var AudioEngine = /** @class */ (function () {
  48936. function AudioEngine() {
  48937. this._audioContext = null;
  48938. this._audioContextInitialized = false;
  48939. this.canUseWebAudio = false;
  48940. this.WarnedWebAudioUnsupported = false;
  48941. this.unlocked = false;
  48942. this.isMP3supported = false;
  48943. this.isOGGsupported = false;
  48944. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48945. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48946. this.canUseWebAudio = true;
  48947. }
  48948. var audioElem = document.createElement('audio');
  48949. try {
  48950. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48951. this.isMP3supported = true;
  48952. }
  48953. }
  48954. catch (e) {
  48955. // protect error during capability check.
  48956. }
  48957. try {
  48958. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48959. this.isOGGsupported = true;
  48960. }
  48961. }
  48962. catch (e) {
  48963. // protect error during capability check.
  48964. }
  48965. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48966. this._unlockiOSaudio();
  48967. }
  48968. else {
  48969. this.unlocked = true;
  48970. }
  48971. }
  48972. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48973. get: function () {
  48974. if (!this._audioContextInitialized) {
  48975. this._initializeAudioContext();
  48976. }
  48977. return this._audioContext;
  48978. },
  48979. enumerable: true,
  48980. configurable: true
  48981. });
  48982. AudioEngine.prototype._unlockiOSaudio = function () {
  48983. var _this = this;
  48984. var unlockaudio = function () {
  48985. if (!_this.audioContext) {
  48986. return;
  48987. }
  48988. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48989. var source = _this.audioContext.createBufferSource();
  48990. source.buffer = buffer;
  48991. source.connect(_this.audioContext.destination);
  48992. source.start(0);
  48993. setTimeout(function () {
  48994. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48995. _this.unlocked = true;
  48996. window.removeEventListener('touchend', unlockaudio, false);
  48997. if (_this.onAudioUnlocked) {
  48998. _this.onAudioUnlocked();
  48999. }
  49000. }
  49001. }, 0);
  49002. };
  49003. window.addEventListener('touchend', unlockaudio, false);
  49004. };
  49005. AudioEngine.prototype._initializeAudioContext = function () {
  49006. try {
  49007. if (this.canUseWebAudio) {
  49008. this._audioContext = new AudioContext();
  49009. // create a global volume gain node
  49010. this.masterGain = this._audioContext.createGain();
  49011. this.masterGain.gain.value = 1;
  49012. this.masterGain.connect(this._audioContext.destination);
  49013. this._audioContextInitialized = true;
  49014. }
  49015. }
  49016. catch (e) {
  49017. this.canUseWebAudio = false;
  49018. BABYLON.Tools.Error("Web Audio: " + e.message);
  49019. }
  49020. };
  49021. AudioEngine.prototype.dispose = function () {
  49022. if (this.canUseWebAudio && this._audioContextInitialized) {
  49023. if (this._connectedAnalyser && this._audioContext) {
  49024. this._connectedAnalyser.stopDebugCanvas();
  49025. this._connectedAnalyser.dispose();
  49026. this.masterGain.disconnect();
  49027. this.masterGain.connect(this._audioContext.destination);
  49028. this._connectedAnalyser = null;
  49029. }
  49030. this.masterGain.gain.value = 1;
  49031. }
  49032. this.WarnedWebAudioUnsupported = false;
  49033. };
  49034. AudioEngine.prototype.getGlobalVolume = function () {
  49035. if (this.canUseWebAudio && this._audioContextInitialized) {
  49036. return this.masterGain.gain.value;
  49037. }
  49038. else {
  49039. return -1;
  49040. }
  49041. };
  49042. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49043. if (this.canUseWebAudio && this._audioContextInitialized) {
  49044. this.masterGain.gain.value = newVolume;
  49045. }
  49046. };
  49047. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49048. if (this._connectedAnalyser) {
  49049. this._connectedAnalyser.stopDebugCanvas();
  49050. }
  49051. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49052. this._connectedAnalyser = analyser;
  49053. this.masterGain.disconnect();
  49054. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49055. }
  49056. };
  49057. return AudioEngine;
  49058. }());
  49059. BABYLON.AudioEngine = AudioEngine;
  49060. })(BABYLON || (BABYLON = {}));
  49061. //# sourceMappingURL=babylon.audioEngine.js.map
  49062. var BABYLON;
  49063. (function (BABYLON) {
  49064. var Sound = /** @class */ (function () {
  49065. /**
  49066. * Create a sound and attach it to a scene
  49067. * @param name Name of your sound
  49068. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49069. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49070. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49071. */
  49072. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49073. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49074. var _this = this;
  49075. this.autoplay = false;
  49076. this.loop = false;
  49077. this.useCustomAttenuation = false;
  49078. this.spatialSound = false;
  49079. this.refDistance = 1;
  49080. this.rolloffFactor = 1;
  49081. this.maxDistance = 100;
  49082. this.distanceModel = "linear";
  49083. this._panningModel = "equalpower";
  49084. this._playbackRate = 1;
  49085. this._streaming = false;
  49086. this._startTime = 0;
  49087. this._startOffset = 0;
  49088. this._position = BABYLON.Vector3.Zero();
  49089. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49090. this._volume = 1;
  49091. this._isReadyToPlay = false;
  49092. this.isPlaying = false;
  49093. this.isPaused = false;
  49094. this._isDirectional = false;
  49095. // Used if you'd like to create a directional sound.
  49096. // If not set, the sound will be omnidirectional
  49097. this._coneInnerAngle = 360;
  49098. this._coneOuterAngle = 360;
  49099. this._coneOuterGain = 0;
  49100. this._isOutputConnected = false;
  49101. this._urlType = "Unknown";
  49102. this.name = name;
  49103. this._scene = scene;
  49104. this._readyToPlayCallback = readyToPlayCallback;
  49105. // Default custom attenuation function is a linear attenuation
  49106. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49107. if (currentDistance < maxDistance) {
  49108. return currentVolume * (1 - currentDistance / maxDistance);
  49109. }
  49110. else {
  49111. return 0;
  49112. }
  49113. };
  49114. if (options) {
  49115. this.autoplay = options.autoplay || false;
  49116. this.loop = options.loop || false;
  49117. // if volume === 0, we need another way to check this option
  49118. if (options.volume !== undefined) {
  49119. this._volume = options.volume;
  49120. }
  49121. this.spatialSound = options.spatialSound || false;
  49122. this.maxDistance = options.maxDistance || 100;
  49123. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49124. this.rolloffFactor = options.rolloffFactor || 1;
  49125. this.refDistance = options.refDistance || 1;
  49126. this.distanceModel = options.distanceModel || "linear";
  49127. this._playbackRate = options.playbackRate || 1;
  49128. this._streaming = options.streaming || false;
  49129. }
  49130. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49131. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49132. this._soundGain.gain.value = this._volume;
  49133. this._inputAudioNode = this._soundGain;
  49134. this._ouputAudioNode = this._soundGain;
  49135. if (this.spatialSound) {
  49136. this._createSpatialParameters();
  49137. }
  49138. this._scene.mainSoundTrack.AddSound(this);
  49139. var validParameter = true;
  49140. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49141. if (urlOrArrayBuffer) {
  49142. if (typeof (urlOrArrayBuffer) === "string")
  49143. this._urlType = "String";
  49144. if (Array.isArray(urlOrArrayBuffer))
  49145. this._urlType = "Array";
  49146. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49147. this._urlType = "ArrayBuffer";
  49148. var urls = [];
  49149. var codecSupportedFound = false;
  49150. switch (this._urlType) {
  49151. case "ArrayBuffer":
  49152. if (urlOrArrayBuffer.byteLength > 0) {
  49153. codecSupportedFound = true;
  49154. this._soundLoaded(urlOrArrayBuffer);
  49155. }
  49156. break;
  49157. case "String":
  49158. urls.push(urlOrArrayBuffer);
  49159. case "Array":
  49160. if (urls.length === 0)
  49161. urls = urlOrArrayBuffer;
  49162. // If we found a supported format, we load it immediately and stop the loop
  49163. for (var i = 0; i < urls.length; i++) {
  49164. var url = urls[i];
  49165. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49166. codecSupportedFound = true;
  49167. }
  49168. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49169. codecSupportedFound = true;
  49170. }
  49171. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49172. codecSupportedFound = true;
  49173. }
  49174. if (url.indexOf("blob:") !== -1) {
  49175. codecSupportedFound = true;
  49176. }
  49177. if (codecSupportedFound) {
  49178. // Loading sound using XHR2
  49179. if (!this._streaming) {
  49180. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49181. }
  49182. else {
  49183. this._htmlAudioElement = new Audio(url);
  49184. this._htmlAudioElement.controls = false;
  49185. this._htmlAudioElement.loop = this.loop;
  49186. this._htmlAudioElement.crossOrigin = "anonymous";
  49187. this._htmlAudioElement.preload = "auto";
  49188. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49189. _this._isReadyToPlay = true;
  49190. if (_this.autoplay) {
  49191. _this.play();
  49192. }
  49193. if (_this._readyToPlayCallback) {
  49194. _this._readyToPlayCallback();
  49195. }
  49196. });
  49197. document.body.appendChild(this._htmlAudioElement);
  49198. }
  49199. break;
  49200. }
  49201. }
  49202. break;
  49203. default:
  49204. validParameter = false;
  49205. break;
  49206. }
  49207. if (!validParameter) {
  49208. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49209. }
  49210. else {
  49211. if (!codecSupportedFound) {
  49212. this._isReadyToPlay = true;
  49213. // Simulating a ready to play event to avoid breaking code path
  49214. if (this._readyToPlayCallback) {
  49215. window.setTimeout(function () {
  49216. if (_this._readyToPlayCallback) {
  49217. _this._readyToPlayCallback();
  49218. }
  49219. }, 1000);
  49220. }
  49221. }
  49222. }
  49223. }
  49224. }
  49225. else {
  49226. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49227. this._scene.mainSoundTrack.AddSound(this);
  49228. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49229. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49230. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49231. }
  49232. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49233. if (this._readyToPlayCallback) {
  49234. window.setTimeout(function () {
  49235. if (_this._readyToPlayCallback) {
  49236. _this._readyToPlayCallback();
  49237. }
  49238. }, 1000);
  49239. }
  49240. }
  49241. }
  49242. Sound.prototype.dispose = function () {
  49243. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49244. if (this.isPlaying) {
  49245. this.stop();
  49246. }
  49247. this._isReadyToPlay = false;
  49248. if (this.soundTrackId === -1) {
  49249. this._scene.mainSoundTrack.RemoveSound(this);
  49250. }
  49251. else {
  49252. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49253. }
  49254. if (this._soundGain) {
  49255. this._soundGain.disconnect();
  49256. this._soundGain = null;
  49257. }
  49258. if (this._soundPanner) {
  49259. this._soundPanner.disconnect();
  49260. this._soundPanner = null;
  49261. }
  49262. if (this._soundSource) {
  49263. this._soundSource.disconnect();
  49264. this._soundSource = null;
  49265. }
  49266. this._audioBuffer = null;
  49267. if (this._htmlAudioElement) {
  49268. this._htmlAudioElement.pause();
  49269. this._htmlAudioElement.src = "";
  49270. document.body.removeChild(this._htmlAudioElement);
  49271. }
  49272. if (this._connectedMesh && this._registerFunc) {
  49273. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49274. this._connectedMesh = null;
  49275. }
  49276. }
  49277. };
  49278. Sound.prototype.isReady = function () {
  49279. return this._isReadyToPlay;
  49280. };
  49281. Sound.prototype._soundLoaded = function (audioData) {
  49282. var _this = this;
  49283. if (!BABYLON.Engine.audioEngine.audioContext) {
  49284. return;
  49285. }
  49286. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49287. _this._audioBuffer = buffer;
  49288. _this._isReadyToPlay = true;
  49289. if (_this.autoplay) {
  49290. _this.play();
  49291. }
  49292. if (_this._readyToPlayCallback) {
  49293. _this._readyToPlayCallback();
  49294. }
  49295. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49296. };
  49297. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49298. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49299. this._audioBuffer = audioBuffer;
  49300. this._isReadyToPlay = true;
  49301. }
  49302. };
  49303. Sound.prototype.updateOptions = function (options) {
  49304. if (options) {
  49305. this.loop = options.loop || this.loop;
  49306. this.maxDistance = options.maxDistance || this.maxDistance;
  49307. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49308. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49309. this.refDistance = options.refDistance || this.refDistance;
  49310. this.distanceModel = options.distanceModel || this.distanceModel;
  49311. this._playbackRate = options.playbackRate || this._playbackRate;
  49312. this._updateSpatialParameters();
  49313. if (this.isPlaying) {
  49314. if (this._streaming) {
  49315. this._htmlAudioElement.playbackRate = this._playbackRate;
  49316. }
  49317. else {
  49318. if (this._soundSource) {
  49319. this._soundSource.playbackRate.value = this._playbackRate;
  49320. }
  49321. }
  49322. }
  49323. }
  49324. };
  49325. Sound.prototype._createSpatialParameters = function () {
  49326. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49327. if (this._scene.headphone) {
  49328. this._panningModel = "HRTF";
  49329. }
  49330. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49331. this._updateSpatialParameters();
  49332. this._soundPanner.connect(this._ouputAudioNode);
  49333. this._inputAudioNode = this._soundPanner;
  49334. }
  49335. };
  49336. Sound.prototype._updateSpatialParameters = function () {
  49337. if (this.spatialSound && this._soundPanner) {
  49338. if (this.useCustomAttenuation) {
  49339. // Tricks to disable in a way embedded Web Audio attenuation
  49340. this._soundPanner.distanceModel = "linear";
  49341. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49342. this._soundPanner.refDistance = 1;
  49343. this._soundPanner.rolloffFactor = 1;
  49344. this._soundPanner.panningModel = this._panningModel;
  49345. }
  49346. else {
  49347. this._soundPanner.distanceModel = this.distanceModel;
  49348. this._soundPanner.maxDistance = this.maxDistance;
  49349. this._soundPanner.refDistance = this.refDistance;
  49350. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49351. this._soundPanner.panningModel = this._panningModel;
  49352. }
  49353. }
  49354. };
  49355. Sound.prototype.switchPanningModelToHRTF = function () {
  49356. this._panningModel = "HRTF";
  49357. this._switchPanningModel();
  49358. };
  49359. Sound.prototype.switchPanningModelToEqualPower = function () {
  49360. this._panningModel = "equalpower";
  49361. this._switchPanningModel();
  49362. };
  49363. Sound.prototype._switchPanningModel = function () {
  49364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49365. this._soundPanner.panningModel = this._panningModel;
  49366. }
  49367. };
  49368. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49370. if (this._isOutputConnected) {
  49371. this._ouputAudioNode.disconnect();
  49372. }
  49373. this._ouputAudioNode.connect(soundTrackAudioNode);
  49374. this._isOutputConnected = true;
  49375. }
  49376. };
  49377. /**
  49378. * Transform this sound into a directional source
  49379. * @param coneInnerAngle Size of the inner cone in degree
  49380. * @param coneOuterAngle Size of the outer cone in degree
  49381. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49382. */
  49383. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49384. if (coneOuterAngle < coneInnerAngle) {
  49385. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49386. return;
  49387. }
  49388. this._coneInnerAngle = coneInnerAngle;
  49389. this._coneOuterAngle = coneOuterAngle;
  49390. this._coneOuterGain = coneOuterGain;
  49391. this._isDirectional = true;
  49392. if (this.isPlaying && this.loop) {
  49393. this.stop();
  49394. this.play();
  49395. }
  49396. };
  49397. Sound.prototype.setPosition = function (newPosition) {
  49398. this._position = newPosition;
  49399. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49400. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49401. }
  49402. };
  49403. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49404. this._localDirection = newLocalDirection;
  49405. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49406. this._updateDirection();
  49407. }
  49408. };
  49409. Sound.prototype._updateDirection = function () {
  49410. if (!this._connectedMesh || !this._soundPanner) {
  49411. return;
  49412. }
  49413. var mat = this._connectedMesh.getWorldMatrix();
  49414. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49415. direction.normalize();
  49416. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49417. };
  49418. Sound.prototype.updateDistanceFromListener = function () {
  49419. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49420. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49421. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49422. }
  49423. };
  49424. Sound.prototype.setAttenuationFunction = function (callback) {
  49425. this._customAttenuationFunction = callback;
  49426. };
  49427. /**
  49428. * Play the sound
  49429. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49430. * @param offset (optional) Start the sound setting it at a specific time
  49431. */
  49432. Sound.prototype.play = function (time, offset) {
  49433. var _this = this;
  49434. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49435. try {
  49436. if (this._startOffset < 0) {
  49437. time = -this._startOffset;
  49438. this._startOffset = 0;
  49439. }
  49440. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49441. if (!this._soundSource || !this._streamingSource) {
  49442. if (this.spatialSound && this._soundPanner) {
  49443. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49444. if (this._isDirectional) {
  49445. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49446. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49447. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49448. if (this._connectedMesh) {
  49449. this._updateDirection();
  49450. }
  49451. else {
  49452. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49453. }
  49454. }
  49455. }
  49456. }
  49457. if (this._streaming) {
  49458. if (!this._streamingSource) {
  49459. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49460. this._htmlAudioElement.onended = function () { _this._onended(); };
  49461. this._htmlAudioElement.playbackRate = this._playbackRate;
  49462. }
  49463. this._streamingSource.disconnect();
  49464. this._streamingSource.connect(this._inputAudioNode);
  49465. this._htmlAudioElement.play();
  49466. }
  49467. else {
  49468. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49469. this._soundSource.buffer = this._audioBuffer;
  49470. this._soundSource.connect(this._inputAudioNode);
  49471. this._soundSource.loop = this.loop;
  49472. this._soundSource.playbackRate.value = this._playbackRate;
  49473. this._soundSource.onended = function () { _this._onended(); };
  49474. if (this._soundSource.buffer) {
  49475. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49476. }
  49477. }
  49478. this._startTime = startTime;
  49479. this.isPlaying = true;
  49480. this.isPaused = false;
  49481. }
  49482. catch (ex) {
  49483. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49484. }
  49485. }
  49486. };
  49487. Sound.prototype._onended = function () {
  49488. this.isPlaying = false;
  49489. if (this.onended) {
  49490. this.onended();
  49491. }
  49492. };
  49493. /**
  49494. * Stop the sound
  49495. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49496. */
  49497. Sound.prototype.stop = function (time) {
  49498. if (this.isPlaying) {
  49499. if (this._streaming) {
  49500. this._htmlAudioElement.pause();
  49501. // Test needed for Firefox or it will generate an Invalid State Error
  49502. if (this._htmlAudioElement.currentTime > 0) {
  49503. this._htmlAudioElement.currentTime = 0;
  49504. }
  49505. }
  49506. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49507. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49508. this._soundSource.stop(stopTime);
  49509. this._soundSource.onended = function () { };
  49510. if (!this.isPaused) {
  49511. this._startOffset = 0;
  49512. }
  49513. }
  49514. this.isPlaying = false;
  49515. }
  49516. };
  49517. Sound.prototype.pause = function () {
  49518. if (this.isPlaying) {
  49519. this.isPaused = true;
  49520. if (this._streaming) {
  49521. this._htmlAudioElement.pause();
  49522. }
  49523. else if (BABYLON.Engine.audioEngine.audioContext) {
  49524. this.stop(0);
  49525. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49526. }
  49527. }
  49528. };
  49529. Sound.prototype.setVolume = function (newVolume, time) {
  49530. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49531. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49532. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49533. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49534. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49535. }
  49536. else {
  49537. this._soundGain.gain.value = newVolume;
  49538. }
  49539. }
  49540. this._volume = newVolume;
  49541. };
  49542. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49543. this._playbackRate = newPlaybackRate;
  49544. if (this.isPlaying) {
  49545. if (this._streaming) {
  49546. this._htmlAudioElement.playbackRate = this._playbackRate;
  49547. }
  49548. else if (this._soundSource) {
  49549. this._soundSource.playbackRate.value = this._playbackRate;
  49550. }
  49551. }
  49552. };
  49553. Sound.prototype.getVolume = function () {
  49554. return this._volume;
  49555. };
  49556. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49557. var _this = this;
  49558. if (this._connectedMesh && this._registerFunc) {
  49559. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49560. this._registerFunc = null;
  49561. }
  49562. this._connectedMesh = meshToConnectTo;
  49563. if (!this.spatialSound) {
  49564. this.spatialSound = true;
  49565. this._createSpatialParameters();
  49566. if (this.isPlaying && this.loop) {
  49567. this.stop();
  49568. this.play();
  49569. }
  49570. }
  49571. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49572. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49573. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49574. };
  49575. Sound.prototype.detachFromMesh = function () {
  49576. if (this._connectedMesh && this._registerFunc) {
  49577. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49578. this._registerFunc = null;
  49579. this._connectedMesh = null;
  49580. }
  49581. };
  49582. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  49583. if (!node.getBoundingInfo) {
  49584. return;
  49585. }
  49586. var mesh = node;
  49587. var boundingInfo = mesh.getBoundingInfo();
  49588. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49589. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49590. this._updateDirection();
  49591. }
  49592. };
  49593. Sound.prototype.clone = function () {
  49594. var _this = this;
  49595. if (!this._streaming) {
  49596. var setBufferAndRun = function () {
  49597. if (_this._isReadyToPlay) {
  49598. clonedSound._audioBuffer = _this.getAudioBuffer();
  49599. clonedSound._isReadyToPlay = true;
  49600. if (clonedSound.autoplay) {
  49601. clonedSound.play();
  49602. }
  49603. }
  49604. else {
  49605. window.setTimeout(setBufferAndRun, 300);
  49606. }
  49607. };
  49608. var currentOptions = {
  49609. autoplay: this.autoplay, loop: this.loop,
  49610. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49611. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49612. refDistance: this.refDistance, distanceModel: this.distanceModel
  49613. };
  49614. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49615. if (this.useCustomAttenuation) {
  49616. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49617. }
  49618. clonedSound.setPosition(this._position);
  49619. clonedSound.setPlaybackRate(this._playbackRate);
  49620. setBufferAndRun();
  49621. return clonedSound;
  49622. }
  49623. else {
  49624. return null;
  49625. }
  49626. };
  49627. Sound.prototype.getAudioBuffer = function () {
  49628. return this._audioBuffer;
  49629. };
  49630. Sound.prototype.serialize = function () {
  49631. var serializationObject = {
  49632. name: this.name,
  49633. url: this.name,
  49634. autoplay: this.autoplay,
  49635. loop: this.loop,
  49636. volume: this._volume,
  49637. spatialSound: this.spatialSound,
  49638. maxDistance: this.maxDistance,
  49639. rolloffFactor: this.rolloffFactor,
  49640. refDistance: this.refDistance,
  49641. distanceModel: this.distanceModel,
  49642. playbackRate: this._playbackRate,
  49643. panningModel: this._panningModel,
  49644. soundTrackId: this.soundTrackId
  49645. };
  49646. if (this.spatialSound) {
  49647. if (this._connectedMesh)
  49648. serializationObject.connectedMeshId = this._connectedMesh.id;
  49649. serializationObject.position = this._position.asArray();
  49650. serializationObject.refDistance = this.refDistance;
  49651. serializationObject.distanceModel = this.distanceModel;
  49652. serializationObject.isDirectional = this._isDirectional;
  49653. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49654. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49655. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49656. serializationObject.coneOuterGain = this._coneOuterGain;
  49657. }
  49658. return serializationObject;
  49659. };
  49660. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49661. var soundName = parsedSound.name;
  49662. var soundUrl;
  49663. if (parsedSound.url) {
  49664. soundUrl = rootUrl + parsedSound.url;
  49665. }
  49666. else {
  49667. soundUrl = rootUrl + soundName;
  49668. }
  49669. var options = {
  49670. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49671. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49672. rolloffFactor: parsedSound.rolloffFactor,
  49673. refDistance: parsedSound.refDistance,
  49674. distanceModel: parsedSound.distanceModel,
  49675. playbackRate: parsedSound.playbackRate
  49676. };
  49677. var newSound;
  49678. if (!sourceSound) {
  49679. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49680. scene._addPendingData(newSound);
  49681. }
  49682. else {
  49683. var setBufferAndRun = function () {
  49684. if (sourceSound._isReadyToPlay) {
  49685. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49686. newSound._isReadyToPlay = true;
  49687. if (newSound.autoplay) {
  49688. newSound.play();
  49689. }
  49690. }
  49691. else {
  49692. window.setTimeout(setBufferAndRun, 300);
  49693. }
  49694. };
  49695. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49696. setBufferAndRun();
  49697. }
  49698. if (parsedSound.position) {
  49699. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49700. newSound.setPosition(soundPosition);
  49701. }
  49702. if (parsedSound.isDirectional) {
  49703. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49704. if (parsedSound.localDirectionToMesh) {
  49705. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49706. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49707. }
  49708. }
  49709. if (parsedSound.connectedMeshId) {
  49710. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49711. if (connectedMesh) {
  49712. newSound.attachToMesh(connectedMesh);
  49713. }
  49714. }
  49715. return newSound;
  49716. };
  49717. return Sound;
  49718. }());
  49719. BABYLON.Sound = Sound;
  49720. })(BABYLON || (BABYLON = {}));
  49721. //# sourceMappingURL=babylon.sound.js.map
  49722. var BABYLON;
  49723. (function (BABYLON) {
  49724. var SoundTrack = /** @class */ (function () {
  49725. function SoundTrack(scene, options) {
  49726. this.id = -1;
  49727. this._isMainTrack = false;
  49728. this._isInitialized = false;
  49729. this._scene = scene;
  49730. this.soundCollection = new Array();
  49731. this._options = options;
  49732. if (!this._isMainTrack) {
  49733. this._scene.soundTracks.push(this);
  49734. this.id = this._scene.soundTracks.length - 1;
  49735. }
  49736. }
  49737. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49738. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49739. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49740. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49741. if (this._options) {
  49742. if (this._options.volume) {
  49743. this._outputAudioNode.gain.value = this._options.volume;
  49744. }
  49745. if (this._options.mainTrack) {
  49746. this._isMainTrack = this._options.mainTrack;
  49747. }
  49748. }
  49749. this._isInitialized = true;
  49750. }
  49751. };
  49752. SoundTrack.prototype.dispose = function () {
  49753. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49754. if (this._connectedAnalyser) {
  49755. this._connectedAnalyser.stopDebugCanvas();
  49756. }
  49757. while (this.soundCollection.length) {
  49758. this.soundCollection[0].dispose();
  49759. }
  49760. if (this._outputAudioNode) {
  49761. this._outputAudioNode.disconnect();
  49762. }
  49763. this._outputAudioNode = null;
  49764. }
  49765. };
  49766. SoundTrack.prototype.AddSound = function (sound) {
  49767. if (!this._isInitialized) {
  49768. this._initializeSoundTrackAudioGraph();
  49769. }
  49770. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49771. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49772. }
  49773. if (sound.soundTrackId) {
  49774. if (sound.soundTrackId === -1) {
  49775. this._scene.mainSoundTrack.RemoveSound(sound);
  49776. }
  49777. else {
  49778. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49779. }
  49780. }
  49781. this.soundCollection.push(sound);
  49782. sound.soundTrackId = this.id;
  49783. };
  49784. SoundTrack.prototype.RemoveSound = function (sound) {
  49785. var index = this.soundCollection.indexOf(sound);
  49786. if (index !== -1) {
  49787. this.soundCollection.splice(index, 1);
  49788. }
  49789. };
  49790. SoundTrack.prototype.setVolume = function (newVolume) {
  49791. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49792. this._outputAudioNode.gain.value = newVolume;
  49793. }
  49794. };
  49795. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49797. for (var i = 0; i < this.soundCollection.length; i++) {
  49798. this.soundCollection[i].switchPanningModelToHRTF();
  49799. }
  49800. }
  49801. };
  49802. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49803. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49804. for (var i = 0; i < this.soundCollection.length; i++) {
  49805. this.soundCollection[i].switchPanningModelToEqualPower();
  49806. }
  49807. }
  49808. };
  49809. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49810. if (this._connectedAnalyser) {
  49811. this._connectedAnalyser.stopDebugCanvas();
  49812. }
  49813. this._connectedAnalyser = analyser;
  49814. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49815. this._outputAudioNode.disconnect();
  49816. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49817. }
  49818. };
  49819. return SoundTrack;
  49820. }());
  49821. BABYLON.SoundTrack = SoundTrack;
  49822. })(BABYLON || (BABYLON = {}));
  49823. //# sourceMappingURL=babylon.soundtrack.js.map
  49824. var BABYLON;
  49825. (function (BABYLON) {
  49826. var Analyser = /** @class */ (function () {
  49827. function Analyser(scene) {
  49828. this.SMOOTHING = 0.75;
  49829. this.FFT_SIZE = 512;
  49830. this.BARGRAPHAMPLITUDE = 256;
  49831. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49832. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49833. this._scene = scene;
  49834. this._audioEngine = BABYLON.Engine.audioEngine;
  49835. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49836. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49837. this._webAudioAnalyser.minDecibels = -140;
  49838. this._webAudioAnalyser.maxDecibels = 0;
  49839. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49840. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49841. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49842. }
  49843. }
  49844. Analyser.prototype.getFrequencyBinCount = function () {
  49845. if (this._audioEngine.canUseWebAudio) {
  49846. return this._webAudioAnalyser.frequencyBinCount;
  49847. }
  49848. else {
  49849. return 0;
  49850. }
  49851. };
  49852. Analyser.prototype.getByteFrequencyData = function () {
  49853. if (this._audioEngine.canUseWebAudio) {
  49854. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49855. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49856. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49857. }
  49858. return this._byteFreqs;
  49859. };
  49860. Analyser.prototype.getByteTimeDomainData = function () {
  49861. if (this._audioEngine.canUseWebAudio) {
  49862. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49863. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49864. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49865. }
  49866. return this._byteTime;
  49867. };
  49868. Analyser.prototype.getFloatFrequencyData = function () {
  49869. if (this._audioEngine.canUseWebAudio) {
  49870. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49871. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49872. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49873. }
  49874. return this._floatFreqs;
  49875. };
  49876. Analyser.prototype.drawDebugCanvas = function () {
  49877. var _this = this;
  49878. if (this._audioEngine.canUseWebAudio) {
  49879. if (!this._debugCanvas) {
  49880. this._debugCanvas = document.createElement("canvas");
  49881. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49882. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49883. this._debugCanvas.style.position = "absolute";
  49884. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49885. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49886. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49887. document.body.appendChild(this._debugCanvas);
  49888. this._registerFunc = function () {
  49889. _this.drawDebugCanvas();
  49890. };
  49891. this._scene.registerBeforeRender(this._registerFunc);
  49892. }
  49893. if (this._registerFunc && this._debugCanvasContext) {
  49894. var workingArray = this.getByteFrequencyData();
  49895. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49896. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49897. // Draw the frequency domain chart.
  49898. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49899. var value = workingArray[i];
  49900. var percent = value / this.BARGRAPHAMPLITUDE;
  49901. var height = this.DEBUGCANVASSIZE.height * percent;
  49902. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49903. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49904. var hue = i / this.getFrequencyBinCount() * 360;
  49905. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49906. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49907. }
  49908. }
  49909. }
  49910. };
  49911. Analyser.prototype.stopDebugCanvas = function () {
  49912. if (this._debugCanvas) {
  49913. if (this._registerFunc) {
  49914. this._scene.unregisterBeforeRender(this._registerFunc);
  49915. this._registerFunc = null;
  49916. }
  49917. document.body.removeChild(this._debugCanvas);
  49918. this._debugCanvas = null;
  49919. this._debugCanvasContext = null;
  49920. }
  49921. };
  49922. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49923. if (this._audioEngine.canUseWebAudio) {
  49924. inputAudioNode.connect(this._webAudioAnalyser);
  49925. this._webAudioAnalyser.connect(outputAudioNode);
  49926. }
  49927. };
  49928. Analyser.prototype.dispose = function () {
  49929. if (this._audioEngine.canUseWebAudio) {
  49930. this._webAudioAnalyser.disconnect();
  49931. }
  49932. };
  49933. return Analyser;
  49934. }());
  49935. BABYLON.Analyser = Analyser;
  49936. })(BABYLON || (BABYLON = {}));
  49937. //# sourceMappingURL=babylon.analyser.js.map
  49938. var BABYLON;
  49939. (function (BABYLON) {
  49940. var CubeTexture = /** @class */ (function (_super) {
  49941. __extends(CubeTexture, _super);
  49942. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49943. if (extensions === void 0) { extensions = null; }
  49944. if (noMipmap === void 0) { noMipmap = false; }
  49945. if (files === void 0) { files = null; }
  49946. if (onLoad === void 0) { onLoad = null; }
  49947. if (onError === void 0) { onError = null; }
  49948. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49949. if (prefiltered === void 0) { prefiltered = false; }
  49950. if (forcedExtension === void 0) { forcedExtension = null; }
  49951. var _this = _super.call(this, scene) || this;
  49952. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49953. _this.name = rootUrl;
  49954. _this.url = rootUrl;
  49955. _this._noMipmap = noMipmap;
  49956. _this.hasAlpha = false;
  49957. _this._format = format;
  49958. _this._prefiltered = prefiltered;
  49959. _this.isCube = true;
  49960. _this._textureMatrix = BABYLON.Matrix.Identity();
  49961. if (prefiltered) {
  49962. _this.gammaSpace = false;
  49963. }
  49964. if (!rootUrl && !files) {
  49965. return _this;
  49966. }
  49967. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49968. var lastDot = rootUrl.lastIndexOf(".");
  49969. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  49970. var isDDS = (extension === ".dds");
  49971. if (!files) {
  49972. if (!isDDS && !extensions) {
  49973. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49974. }
  49975. files = [];
  49976. if (extensions) {
  49977. for (var index = 0; index < extensions.length; index++) {
  49978. files.push(rootUrl + extensions[index]);
  49979. }
  49980. }
  49981. }
  49982. if (!_this._texture) {
  49983. if (!scene.useDelayedTextureLoading) {
  49984. if (prefiltered) {
  49985. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49986. }
  49987. else {
  49988. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49989. }
  49990. }
  49991. else {
  49992. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49993. }
  49994. }
  49995. else if (onLoad) {
  49996. if (_this._texture.isReady) {
  49997. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49998. }
  49999. else {
  50000. _this._texture.onLoadedObservable.add(onLoad);
  50001. }
  50002. }
  50003. return _this;
  50004. }
  50005. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50006. return new CubeTexture("", scene, null, noMipmap, files);
  50007. };
  50008. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50009. if (forcedExtension === void 0) { forcedExtension = null; }
  50010. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50011. };
  50012. // Methods
  50013. CubeTexture.prototype.delayLoad = function () {
  50014. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50015. return;
  50016. }
  50017. var scene = this.getScene();
  50018. if (!scene) {
  50019. return;
  50020. }
  50021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50022. this._texture = this._getFromCache(this.url, this._noMipmap);
  50023. if (!this._texture) {
  50024. if (this._prefiltered) {
  50025. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50026. }
  50027. else {
  50028. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50029. }
  50030. }
  50031. };
  50032. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50033. return this._textureMatrix;
  50034. };
  50035. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50036. this._textureMatrix = value;
  50037. };
  50038. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50039. var texture = BABYLON.SerializationHelper.Parse(function () {
  50040. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50041. }, parsedTexture, scene);
  50042. // Animations
  50043. if (parsedTexture.animations) {
  50044. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50045. var parsedAnimation = parsedTexture.animations[animationIndex];
  50046. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50047. }
  50048. }
  50049. return texture;
  50050. };
  50051. CubeTexture.prototype.clone = function () {
  50052. var _this = this;
  50053. return BABYLON.SerializationHelper.Clone(function () {
  50054. var scene = _this.getScene();
  50055. if (!scene) {
  50056. return _this;
  50057. }
  50058. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50059. }, this);
  50060. };
  50061. return CubeTexture;
  50062. }(BABYLON.BaseTexture));
  50063. BABYLON.CubeTexture = CubeTexture;
  50064. })(BABYLON || (BABYLON = {}));
  50065. //# sourceMappingURL=babylon.cubeTexture.js.map
  50066. var BABYLON;
  50067. (function (BABYLON) {
  50068. var RenderTargetTexture = /** @class */ (function (_super) {
  50069. __extends(RenderTargetTexture, _super);
  50070. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50071. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50072. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50073. if (isCube === void 0) { isCube = false; }
  50074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50075. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50076. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50077. if (isMulti === void 0) { isMulti = false; }
  50078. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50079. _this.isCube = isCube;
  50080. /**
  50081. * Use this list to define the list of mesh you want to render.
  50082. */
  50083. _this.renderList = new Array();
  50084. _this.renderParticles = true;
  50085. _this.renderSprites = false;
  50086. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50087. _this.ignoreCameraViewport = false;
  50088. // Events
  50089. /**
  50090. * An event triggered when the texture is unbind.
  50091. * @type {BABYLON.Observable}
  50092. */
  50093. _this.onBeforeBindObservable = new BABYLON.Observable();
  50094. /**
  50095. * An event triggered when the texture is unbind.
  50096. * @type {BABYLON.Observable}
  50097. */
  50098. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50099. /**
  50100. * An event triggered before rendering the texture
  50101. * @type {BABYLON.Observable}
  50102. */
  50103. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50104. /**
  50105. * An event triggered after rendering the texture
  50106. * @type {BABYLON.Observable}
  50107. */
  50108. _this.onAfterRenderObservable = new BABYLON.Observable();
  50109. /**
  50110. * An event triggered after the texture clear
  50111. * @type {BABYLON.Observable}
  50112. */
  50113. _this.onClearObservable = new BABYLON.Observable();
  50114. _this._currentRefreshId = -1;
  50115. _this._refreshRate = 1;
  50116. _this._samples = 1;
  50117. scene = _this.getScene();
  50118. if (!scene) {
  50119. return _this;
  50120. }
  50121. _this._engine = scene.getEngine();
  50122. _this.name = name;
  50123. _this.isRenderTarget = true;
  50124. _this._initialSizeParameter = size;
  50125. _this._processSizeParameter(size);
  50126. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50127. });
  50128. _this._generateMipMaps = generateMipMaps ? true : false;
  50129. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50130. // Rendering groups
  50131. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50132. if (isMulti) {
  50133. return _this;
  50134. }
  50135. _this._renderTargetOptions = {
  50136. generateMipMaps: generateMipMaps,
  50137. type: type,
  50138. samplingMode: samplingMode,
  50139. generateDepthBuffer: generateDepthBuffer,
  50140. generateStencilBuffer: generateStencilBuffer
  50141. };
  50142. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50143. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50144. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50145. }
  50146. if (isCube) {
  50147. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50148. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50149. _this._textureMatrix = BABYLON.Matrix.Identity();
  50150. }
  50151. else {
  50152. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50153. }
  50154. return _this;
  50155. }
  50156. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50157. get: function () {
  50158. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50159. },
  50160. enumerable: true,
  50161. configurable: true
  50162. });
  50163. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50164. get: function () {
  50165. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50171. get: function () {
  50172. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50173. },
  50174. enumerable: true,
  50175. configurable: true
  50176. });
  50177. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50178. set: function (callback) {
  50179. if (this._onAfterUnbindObserver) {
  50180. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50181. }
  50182. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50183. },
  50184. enumerable: true,
  50185. configurable: true
  50186. });
  50187. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50188. set: function (callback) {
  50189. if (this._onBeforeRenderObserver) {
  50190. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50191. }
  50192. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50198. set: function (callback) {
  50199. if (this._onAfterRenderObserver) {
  50200. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50201. }
  50202. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50203. },
  50204. enumerable: true,
  50205. configurable: true
  50206. });
  50207. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50208. set: function (callback) {
  50209. if (this._onClearObserver) {
  50210. this.onClearObservable.remove(this._onClearObserver);
  50211. }
  50212. this._onClearObserver = this.onClearObservable.add(callback);
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50218. get: function () {
  50219. return this._renderTargetOptions;
  50220. },
  50221. enumerable: true,
  50222. configurable: true
  50223. });
  50224. RenderTargetTexture.prototype._onRatioRescale = function () {
  50225. if (this._sizeRatio) {
  50226. this.resize(this._initialSizeParameter);
  50227. }
  50228. };
  50229. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50230. if (size.ratio) {
  50231. this._sizeRatio = size.ratio;
  50232. this._size = {
  50233. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50234. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50235. };
  50236. }
  50237. else {
  50238. this._size = size;
  50239. }
  50240. };
  50241. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50242. get: function () {
  50243. return this._samples;
  50244. },
  50245. set: function (value) {
  50246. if (this._samples === value) {
  50247. return;
  50248. }
  50249. var scene = this.getScene();
  50250. if (!scene) {
  50251. return;
  50252. }
  50253. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50254. },
  50255. enumerable: true,
  50256. configurable: true
  50257. });
  50258. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50259. this._currentRefreshId = -1;
  50260. };
  50261. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50262. get: function () {
  50263. return this._refreshRate;
  50264. },
  50265. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50266. set: function (value) {
  50267. this._refreshRate = value;
  50268. this.resetRefreshCounter();
  50269. },
  50270. enumerable: true,
  50271. configurable: true
  50272. });
  50273. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50274. if (!this._postProcessManager) {
  50275. var scene = this.getScene();
  50276. if (!scene) {
  50277. return;
  50278. }
  50279. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50280. this._postProcesses = new Array();
  50281. }
  50282. this._postProcesses.push(postProcess);
  50283. this._postProcesses[0].autoClear = false;
  50284. };
  50285. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50286. if (!this._postProcesses) {
  50287. return;
  50288. }
  50289. if (dispose) {
  50290. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50291. var postProcess = _a[_i];
  50292. postProcess.dispose();
  50293. }
  50294. }
  50295. this._postProcesses = [];
  50296. };
  50297. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50298. if (!this._postProcesses) {
  50299. return;
  50300. }
  50301. var index = this._postProcesses.indexOf(postProcess);
  50302. if (index === -1) {
  50303. return;
  50304. }
  50305. this._postProcesses.splice(index, 1);
  50306. if (this._postProcesses.length > 0) {
  50307. this._postProcesses[0].autoClear = false;
  50308. }
  50309. };
  50310. RenderTargetTexture.prototype._shouldRender = function () {
  50311. if (this._currentRefreshId === -1) {
  50312. this._currentRefreshId = 1;
  50313. return true;
  50314. }
  50315. if (this.refreshRate === this._currentRefreshId) {
  50316. this._currentRefreshId = 1;
  50317. return true;
  50318. }
  50319. this._currentRefreshId++;
  50320. return false;
  50321. };
  50322. RenderTargetTexture.prototype.getRenderSize = function () {
  50323. if (this._size.width) {
  50324. return this._size.width;
  50325. }
  50326. return this._size;
  50327. };
  50328. RenderTargetTexture.prototype.getRenderWidth = function () {
  50329. if (this._size.width) {
  50330. return this._size.width;
  50331. }
  50332. return this._size;
  50333. };
  50334. RenderTargetTexture.prototype.getRenderHeight = function () {
  50335. if (this._size.width) {
  50336. return this._size.height;
  50337. }
  50338. return this._size;
  50339. };
  50340. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50341. get: function () {
  50342. return true;
  50343. },
  50344. enumerable: true,
  50345. configurable: true
  50346. });
  50347. RenderTargetTexture.prototype.scale = function (ratio) {
  50348. var newSize = this.getRenderSize() * ratio;
  50349. this.resize(newSize);
  50350. };
  50351. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50352. if (this.isCube) {
  50353. return this._textureMatrix;
  50354. }
  50355. return _super.prototype.getReflectionTextureMatrix.call(this);
  50356. };
  50357. RenderTargetTexture.prototype.resize = function (size) {
  50358. this.releaseInternalTexture();
  50359. var scene = this.getScene();
  50360. if (!scene) {
  50361. return;
  50362. }
  50363. this._processSizeParameter(size);
  50364. if (this.isCube) {
  50365. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50366. }
  50367. else {
  50368. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50369. }
  50370. };
  50371. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50372. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50373. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50374. var scene = this.getScene();
  50375. if (!scene) {
  50376. return;
  50377. }
  50378. var engine = scene.getEngine();
  50379. if (this.useCameraPostProcesses !== undefined) {
  50380. useCameraPostProcess = this.useCameraPostProcesses;
  50381. }
  50382. if (this._waitingRenderList) {
  50383. this.renderList = [];
  50384. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50385. var id = this._waitingRenderList[index];
  50386. var mesh_1 = scene.getMeshByID(id);
  50387. if (mesh_1) {
  50388. this.renderList.push(mesh_1);
  50389. }
  50390. }
  50391. delete this._waitingRenderList;
  50392. }
  50393. // Is predicate defined?
  50394. if (this.renderListPredicate) {
  50395. if (this.renderList) {
  50396. this.renderList.splice(0); // Clear previous renderList
  50397. }
  50398. else {
  50399. this.renderList = [];
  50400. }
  50401. var scene = this.getScene();
  50402. if (!scene) {
  50403. return;
  50404. }
  50405. var sceneMeshes = scene.meshes;
  50406. for (var index = 0; index < sceneMeshes.length; index++) {
  50407. var mesh = sceneMeshes[index];
  50408. if (this.renderListPredicate(mesh)) {
  50409. this.renderList.push(mesh);
  50410. }
  50411. }
  50412. }
  50413. this.onBeforeBindObservable.notifyObservers(this);
  50414. // Set custom projection.
  50415. // Needs to be before binding to prevent changing the aspect ratio.
  50416. var camera;
  50417. if (this.activeCamera) {
  50418. camera = this.activeCamera;
  50419. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50420. if (this.activeCamera !== scene.activeCamera) {
  50421. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50422. }
  50423. }
  50424. else {
  50425. camera = scene.activeCamera;
  50426. if (camera) {
  50427. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50428. }
  50429. }
  50430. // Prepare renderingManager
  50431. this._renderingManager.reset();
  50432. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50433. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50434. var sceneRenderId = scene.getRenderId();
  50435. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50436. var mesh = currentRenderList[meshIndex];
  50437. if (mesh) {
  50438. if (!mesh.isReady()) {
  50439. // Reset _currentRefreshId
  50440. this.resetRefreshCounter();
  50441. continue;
  50442. }
  50443. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50444. var isMasked = void 0;
  50445. if (!this.renderList && camera) {
  50446. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50447. }
  50448. else {
  50449. isMasked = false;
  50450. }
  50451. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50452. mesh._activate(sceneRenderId);
  50453. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50454. var subMesh = mesh.subMeshes[subIndex];
  50455. scene._activeIndices.addCount(subMesh.indexCount, false);
  50456. this._renderingManager.dispatch(subMesh);
  50457. }
  50458. }
  50459. }
  50460. }
  50461. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50462. var particleSystem = scene.particleSystems[particleIndex];
  50463. var emitter = particleSystem.emitter;
  50464. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50465. continue;
  50466. }
  50467. if (currentRenderList.indexOf(emitter) >= 0) {
  50468. this._renderingManager.dispatchParticles(particleSystem);
  50469. }
  50470. }
  50471. if (this.isCube) {
  50472. for (var face = 0; face < 6; face++) {
  50473. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50474. scene.incrementRenderId();
  50475. scene.resetCachedMaterial();
  50476. }
  50477. }
  50478. else {
  50479. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50480. }
  50481. this.onAfterUnbindObservable.notifyObservers(this);
  50482. if (scene.activeCamera) {
  50483. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50484. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50485. }
  50486. engine.setViewport(scene.activeCamera.viewport);
  50487. }
  50488. scene.resetCachedMaterial();
  50489. };
  50490. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50491. var minimum = 128;
  50492. var x = renderDimension * scale;
  50493. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50494. // Ensure we don't exceed the render dimension (while staying POT)
  50495. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50496. };
  50497. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50498. var _this = this;
  50499. var scene = this.getScene();
  50500. if (!scene) {
  50501. return;
  50502. }
  50503. var engine = scene.getEngine();
  50504. if (!this._texture) {
  50505. return;
  50506. }
  50507. // Bind
  50508. if (this._postProcessManager) {
  50509. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50510. }
  50511. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50512. if (this._texture) {
  50513. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50514. }
  50515. }
  50516. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50517. // Clear
  50518. if (this.onClearObservable.hasObservers()) {
  50519. this.onClearObservable.notifyObservers(engine);
  50520. }
  50521. else {
  50522. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50523. }
  50524. if (!this._doNotChangeAspectRatio) {
  50525. scene.updateTransformMatrix(true);
  50526. }
  50527. // Render
  50528. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50529. if (this._postProcessManager) {
  50530. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50531. }
  50532. else if (useCameraPostProcess) {
  50533. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50534. }
  50535. if (!this._doNotChangeAspectRatio) {
  50536. scene.updateTransformMatrix(true);
  50537. }
  50538. // Dump ?
  50539. if (dumpForDebug) {
  50540. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50541. }
  50542. // Unbind
  50543. if (!this.isCube || faceIndex === 5) {
  50544. if (this.isCube) {
  50545. if (faceIndex === 5) {
  50546. engine.generateMipMapsForCubemap(this._texture);
  50547. }
  50548. }
  50549. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50550. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50551. });
  50552. }
  50553. else {
  50554. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50555. }
  50556. };
  50557. /**
  50558. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50559. * This allowed control for front to back rendering or reversly depending of the special needs.
  50560. *
  50561. * @param renderingGroupId The rendering group id corresponding to its index
  50562. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50563. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50564. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50565. */
  50566. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50567. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50568. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50569. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50570. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50571. };
  50572. /**
  50573. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50574. *
  50575. * @param renderingGroupId The rendering group id corresponding to its index
  50576. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50577. */
  50578. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50579. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50580. };
  50581. RenderTargetTexture.prototype.clone = function () {
  50582. var textureSize = this.getSize();
  50583. 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);
  50584. // Base texture
  50585. newTexture.hasAlpha = this.hasAlpha;
  50586. newTexture.level = this.level;
  50587. // RenderTarget Texture
  50588. newTexture.coordinatesMode = this.coordinatesMode;
  50589. if (this.renderList) {
  50590. newTexture.renderList = this.renderList.slice(0);
  50591. }
  50592. return newTexture;
  50593. };
  50594. RenderTargetTexture.prototype.serialize = function () {
  50595. if (!this.name) {
  50596. return null;
  50597. }
  50598. var serializationObject = _super.prototype.serialize.call(this);
  50599. serializationObject.renderTargetSize = this.getRenderSize();
  50600. serializationObject.renderList = [];
  50601. if (this.renderList) {
  50602. for (var index = 0; index < this.renderList.length; index++) {
  50603. serializationObject.renderList.push(this.renderList[index].id);
  50604. }
  50605. }
  50606. return serializationObject;
  50607. };
  50608. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50609. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50610. var objBuffer = this.getInternalTexture();
  50611. var scene = this.getScene();
  50612. if (objBuffer && scene) {
  50613. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50614. }
  50615. };
  50616. RenderTargetTexture.prototype.dispose = function () {
  50617. if (this._postProcessManager) {
  50618. this._postProcessManager.dispose();
  50619. this._postProcessManager = null;
  50620. }
  50621. this.clearPostProcesses(true);
  50622. if (this._resizeObserver) {
  50623. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50624. this._resizeObserver = null;
  50625. }
  50626. this.renderList = null;
  50627. // Remove from custom render targets
  50628. var scene = this.getScene();
  50629. if (!scene) {
  50630. return;
  50631. }
  50632. var index = scene.customRenderTargets.indexOf(this);
  50633. if (index >= 0) {
  50634. scene.customRenderTargets.splice(index, 1);
  50635. }
  50636. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50637. var camera = _a[_i];
  50638. index = camera.customRenderTargets.indexOf(this);
  50639. if (index >= 0) {
  50640. camera.customRenderTargets.splice(index, 1);
  50641. }
  50642. }
  50643. _super.prototype.dispose.call(this);
  50644. };
  50645. RenderTargetTexture.prototype._rebuild = function () {
  50646. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50647. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50648. }
  50649. if (this._postProcessManager) {
  50650. this._postProcessManager._rebuild();
  50651. }
  50652. };
  50653. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50654. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50655. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50656. return RenderTargetTexture;
  50657. }(BABYLON.Texture));
  50658. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50659. })(BABYLON || (BABYLON = {}));
  50660. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50661. var BABYLON;
  50662. (function (BABYLON) {
  50663. ;
  50664. var MultiRenderTarget = /** @class */ (function (_super) {
  50665. __extends(MultiRenderTarget, _super);
  50666. function MultiRenderTarget(name, size, count, scene, options) {
  50667. var _this = this;
  50668. options = options || {};
  50669. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50670. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50671. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50672. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50673. _this._engine = scene.getEngine();
  50674. if (!_this.isSupported) {
  50675. _this.dispose();
  50676. return;
  50677. }
  50678. var types = [];
  50679. var samplingModes = [];
  50680. for (var i = 0; i < count; i++) {
  50681. if (options.types && options.types[i]) {
  50682. types.push(options.types[i]);
  50683. }
  50684. else {
  50685. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50686. }
  50687. if (options.samplingModes && options.samplingModes[i]) {
  50688. samplingModes.push(options.samplingModes[i]);
  50689. }
  50690. else {
  50691. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50692. }
  50693. }
  50694. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50695. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50696. _this._size = size;
  50697. _this._multiRenderTargetOptions = {
  50698. samplingModes: samplingModes,
  50699. generateMipMaps: generateMipMaps,
  50700. generateDepthBuffer: generateDepthBuffer,
  50701. generateStencilBuffer: generateStencilBuffer,
  50702. generateDepthTexture: generateDepthTexture,
  50703. types: types,
  50704. textureCount: count
  50705. };
  50706. _this._createInternalTextures();
  50707. _this._createTextures();
  50708. return _this;
  50709. }
  50710. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50711. get: function () {
  50712. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50713. },
  50714. enumerable: true,
  50715. configurable: true
  50716. });
  50717. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50718. get: function () {
  50719. return this._textures;
  50720. },
  50721. enumerable: true,
  50722. configurable: true
  50723. });
  50724. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50725. get: function () {
  50726. return this._textures[this._textures.length - 1];
  50727. },
  50728. enumerable: true,
  50729. configurable: true
  50730. });
  50731. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50732. set: function (wrap) {
  50733. if (this._textures) {
  50734. for (var i = 0; i < this._textures.length; i++) {
  50735. this._textures[i].wrapU = wrap;
  50736. }
  50737. }
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50743. set: function (wrap) {
  50744. if (this._textures) {
  50745. for (var i = 0; i < this._textures.length; i++) {
  50746. this._textures[i].wrapV = wrap;
  50747. }
  50748. }
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. MultiRenderTarget.prototype._rebuild = function () {
  50754. this.releaseInternalTextures();
  50755. this._createInternalTextures();
  50756. for (var i = 0; i < this._internalTextures.length; i++) {
  50757. var texture = this._textures[i];
  50758. texture._texture = this._internalTextures[i];
  50759. }
  50760. // Keeps references to frame buffer and stencil/depth buffer
  50761. this._texture = this._internalTextures[0];
  50762. };
  50763. MultiRenderTarget.prototype._createInternalTextures = function () {
  50764. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50765. };
  50766. MultiRenderTarget.prototype._createTextures = function () {
  50767. this._textures = [];
  50768. for (var i = 0; i < this._internalTextures.length; i++) {
  50769. var texture = new BABYLON.Texture(null, this.getScene());
  50770. texture._texture = this._internalTextures[i];
  50771. this._textures.push(texture);
  50772. }
  50773. // Keeps references to frame buffer and stencil/depth buffer
  50774. this._texture = this._internalTextures[0];
  50775. };
  50776. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50777. get: function () {
  50778. return this._samples;
  50779. },
  50780. set: function (value) {
  50781. if (this._samples === value) {
  50782. return;
  50783. }
  50784. for (var i = 0; i < this._internalTextures.length; i++) {
  50785. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50786. }
  50787. },
  50788. enumerable: true,
  50789. configurable: true
  50790. });
  50791. MultiRenderTarget.prototype.resize = function (size) {
  50792. this.releaseInternalTextures();
  50793. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50794. this._createInternalTextures();
  50795. };
  50796. MultiRenderTarget.prototype.dispose = function () {
  50797. this.releaseInternalTextures();
  50798. _super.prototype.dispose.call(this);
  50799. };
  50800. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50801. if (!this._internalTextures) {
  50802. return;
  50803. }
  50804. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50805. if (this._internalTextures[i] !== undefined) {
  50806. this._internalTextures[i].dispose();
  50807. this._internalTextures.splice(i, 1);
  50808. }
  50809. }
  50810. };
  50811. return MultiRenderTarget;
  50812. }(BABYLON.RenderTargetTexture));
  50813. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50814. })(BABYLON || (BABYLON = {}));
  50815. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. var MirrorTexture = /** @class */ (function (_super) {
  50819. __extends(MirrorTexture, _super);
  50820. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50822. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50823. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50824. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50825. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50826. _this._transformMatrix = BABYLON.Matrix.Zero();
  50827. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50828. _this._adaptiveBlurKernel = 0;
  50829. _this._blurKernelX = 0;
  50830. _this._blurKernelY = 0;
  50831. _this._blurRatio = 1.0;
  50832. _this.ignoreCameraViewport = true;
  50833. _this.onBeforeRenderObservable.add(function () {
  50834. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50835. _this._savedViewMatrix = scene.getViewMatrix();
  50836. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50837. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50838. scene.clipPlane = _this.mirrorPlane;
  50839. scene.getEngine().cullBackFaces = false;
  50840. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50841. });
  50842. _this.onAfterRenderObservable.add(function () {
  50843. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50844. scene.getEngine().cullBackFaces = true;
  50845. scene._mirroredCameraPosition = null;
  50846. delete scene.clipPlane;
  50847. });
  50848. return _this;
  50849. }
  50850. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50851. get: function () {
  50852. return this._blurRatio;
  50853. },
  50854. set: function (value) {
  50855. if (this._blurRatio === value) {
  50856. return;
  50857. }
  50858. this._blurRatio = value;
  50859. this._preparePostProcesses();
  50860. },
  50861. enumerable: true,
  50862. configurable: true
  50863. });
  50864. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50865. set: function (value) {
  50866. this._adaptiveBlurKernel = value;
  50867. this._autoComputeBlurKernel();
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50873. set: function (value) {
  50874. this.blurKernelX = value;
  50875. this.blurKernelY = value;
  50876. },
  50877. enumerable: true,
  50878. configurable: true
  50879. });
  50880. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50881. get: function () {
  50882. return this._blurKernelX;
  50883. },
  50884. set: function (value) {
  50885. if (this._blurKernelX === value) {
  50886. return;
  50887. }
  50888. this._blurKernelX = value;
  50889. this._preparePostProcesses();
  50890. },
  50891. enumerable: true,
  50892. configurable: true
  50893. });
  50894. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50895. get: function () {
  50896. return this._blurKernelY;
  50897. },
  50898. set: function (value) {
  50899. if (this._blurKernelY === value) {
  50900. return;
  50901. }
  50902. this._blurKernelY = value;
  50903. this._preparePostProcesses();
  50904. },
  50905. enumerable: true,
  50906. configurable: true
  50907. });
  50908. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50909. var engine = this.getScene().getEngine();
  50910. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50911. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50912. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50913. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50914. };
  50915. MirrorTexture.prototype._onRatioRescale = function () {
  50916. if (this._sizeRatio) {
  50917. this.resize(this._initialSizeParameter);
  50918. if (!this._adaptiveBlurKernel) {
  50919. this._preparePostProcesses();
  50920. }
  50921. }
  50922. if (this._adaptiveBlurKernel) {
  50923. this._autoComputeBlurKernel();
  50924. }
  50925. };
  50926. MirrorTexture.prototype._preparePostProcesses = function () {
  50927. this.clearPostProcesses(true);
  50928. if (this._blurKernelX && this._blurKernelY) {
  50929. var engine = this.getScene().getEngine();
  50930. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50931. 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);
  50932. this._blurX.autoClear = false;
  50933. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50934. this._blurX.outputTexture = this._texture;
  50935. }
  50936. else {
  50937. this._blurX.alwaysForcePOT = true;
  50938. }
  50939. 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);
  50940. this._blurY.autoClear = false;
  50941. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50942. this.addPostProcess(this._blurX);
  50943. this.addPostProcess(this._blurY);
  50944. }
  50945. else {
  50946. if (this._blurY) {
  50947. this.removePostProcess(this._blurY);
  50948. this._blurY.dispose();
  50949. this._blurY = null;
  50950. }
  50951. if (this._blurX) {
  50952. this.removePostProcess(this._blurX);
  50953. this._blurX.dispose();
  50954. this._blurX = null;
  50955. }
  50956. }
  50957. };
  50958. MirrorTexture.prototype.clone = function () {
  50959. var scene = this.getScene();
  50960. if (!scene) {
  50961. return this;
  50962. }
  50963. var textureSize = this.getSize();
  50964. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50965. // Base texture
  50966. newTexture.hasAlpha = this.hasAlpha;
  50967. newTexture.level = this.level;
  50968. // Mirror Texture
  50969. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50970. if (this.renderList) {
  50971. newTexture.renderList = this.renderList.slice(0);
  50972. }
  50973. return newTexture;
  50974. };
  50975. MirrorTexture.prototype.serialize = function () {
  50976. if (!this.name) {
  50977. return null;
  50978. }
  50979. var serializationObject = _super.prototype.serialize.call(this);
  50980. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50981. return serializationObject;
  50982. };
  50983. return MirrorTexture;
  50984. }(BABYLON.RenderTargetTexture));
  50985. BABYLON.MirrorTexture = MirrorTexture;
  50986. })(BABYLON || (BABYLON = {}));
  50987. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50988. var BABYLON;
  50989. (function (BABYLON) {
  50990. /**
  50991. * Creates a refraction texture used by refraction channel of the standard material.
  50992. * @param name the texture name
  50993. * @param size size of the underlying texture
  50994. * @param scene root scene
  50995. */
  50996. var RefractionTexture = /** @class */ (function (_super) {
  50997. __extends(RefractionTexture, _super);
  50998. function RefractionTexture(name, size, scene, generateMipMaps) {
  50999. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51000. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51001. _this.depth = 2.0;
  51002. _this.onBeforeRenderObservable.add(function () {
  51003. scene.clipPlane = _this.refractionPlane;
  51004. });
  51005. _this.onAfterRenderObservable.add(function () {
  51006. delete scene.clipPlane;
  51007. });
  51008. return _this;
  51009. }
  51010. RefractionTexture.prototype.clone = function () {
  51011. var scene = this.getScene();
  51012. if (!scene) {
  51013. return this;
  51014. }
  51015. var textureSize = this.getSize();
  51016. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51017. // Base texture
  51018. newTexture.hasAlpha = this.hasAlpha;
  51019. newTexture.level = this.level;
  51020. // Refraction Texture
  51021. newTexture.refractionPlane = this.refractionPlane.clone();
  51022. if (this.renderList) {
  51023. newTexture.renderList = this.renderList.slice(0);
  51024. }
  51025. newTexture.depth = this.depth;
  51026. return newTexture;
  51027. };
  51028. RefractionTexture.prototype.serialize = function () {
  51029. if (!this.name) {
  51030. return null;
  51031. }
  51032. var serializationObject = _super.prototype.serialize.call(this);
  51033. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51034. serializationObject.depth = this.depth;
  51035. return serializationObject;
  51036. };
  51037. return RefractionTexture;
  51038. }(BABYLON.RenderTargetTexture));
  51039. BABYLON.RefractionTexture = RefractionTexture;
  51040. })(BABYLON || (BABYLON = {}));
  51041. //# sourceMappingURL=babylon.refractionTexture.js.map
  51042. var BABYLON;
  51043. (function (BABYLON) {
  51044. var DynamicTexture = /** @class */ (function (_super) {
  51045. __extends(DynamicTexture, _super);
  51046. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51047. if (scene === void 0) { scene = null; }
  51048. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51049. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51050. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51051. _this.name = name;
  51052. _this._engine = _this.getScene().getEngine();
  51053. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51054. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51055. _this._generateMipMaps = generateMipMaps;
  51056. if (options.getContext) {
  51057. _this._canvas = options;
  51058. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51059. }
  51060. else {
  51061. _this._canvas = document.createElement("canvas");
  51062. if (options.width) {
  51063. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51064. }
  51065. else {
  51066. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51067. }
  51068. }
  51069. var textureSize = _this.getSize();
  51070. _this._canvas.width = textureSize.width;
  51071. _this._canvas.height = textureSize.height;
  51072. _this._context = _this._canvas.getContext("2d");
  51073. return _this;
  51074. }
  51075. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51076. get: function () {
  51077. return true;
  51078. },
  51079. enumerable: true,
  51080. configurable: true
  51081. });
  51082. DynamicTexture.prototype._recreate = function (textureSize) {
  51083. this._canvas.width = textureSize.width;
  51084. this._canvas.height = textureSize.height;
  51085. this.releaseInternalTexture();
  51086. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51087. };
  51088. DynamicTexture.prototype.scale = function (ratio) {
  51089. var textureSize = this.getSize();
  51090. textureSize.width *= ratio;
  51091. textureSize.height *= ratio;
  51092. this._recreate(textureSize);
  51093. };
  51094. DynamicTexture.prototype.scaleTo = function (width, height) {
  51095. var textureSize = this.getSize();
  51096. textureSize.width = width;
  51097. textureSize.height = height;
  51098. this._recreate(textureSize);
  51099. };
  51100. DynamicTexture.prototype.getContext = function () {
  51101. return this._context;
  51102. };
  51103. DynamicTexture.prototype.clear = function () {
  51104. var size = this.getSize();
  51105. this._context.fillRect(0, 0, size.width, size.height);
  51106. };
  51107. DynamicTexture.prototype.update = function (invertY) {
  51108. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51109. };
  51110. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51111. if (update === void 0) { update = true; }
  51112. var size = this.getSize();
  51113. if (clearColor) {
  51114. this._context.fillStyle = clearColor;
  51115. this._context.fillRect(0, 0, size.width, size.height);
  51116. }
  51117. this._context.font = font;
  51118. if (x === null || x === undefined) {
  51119. var textSize = this._context.measureText(text);
  51120. x = (size.width - textSize.width) / 2;
  51121. }
  51122. if (y === null || y === undefined) {
  51123. var fontSize = parseInt((font.replace(/\D/g, '')));
  51124. ;
  51125. y = (size.height / 2) + (fontSize / 3.65);
  51126. }
  51127. this._context.fillStyle = color;
  51128. this._context.fillText(text, x, y);
  51129. if (update) {
  51130. this.update(invertY);
  51131. }
  51132. };
  51133. DynamicTexture.prototype.clone = function () {
  51134. var scene = this.getScene();
  51135. if (!scene) {
  51136. return this;
  51137. }
  51138. var textureSize = this.getSize();
  51139. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51140. // Base texture
  51141. newTexture.hasAlpha = this.hasAlpha;
  51142. newTexture.level = this.level;
  51143. // Dynamic Texture
  51144. newTexture.wrapU = this.wrapU;
  51145. newTexture.wrapV = this.wrapV;
  51146. return newTexture;
  51147. };
  51148. DynamicTexture.prototype._rebuild = function () {
  51149. this.update();
  51150. };
  51151. return DynamicTexture;
  51152. }(BABYLON.Texture));
  51153. BABYLON.DynamicTexture = DynamicTexture;
  51154. })(BABYLON || (BABYLON = {}));
  51155. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51156. var BABYLON;
  51157. (function (BABYLON) {
  51158. var VideoTexture = /** @class */ (function (_super) {
  51159. __extends(VideoTexture, _super);
  51160. /**
  51161. * Creates a video texture.
  51162. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51163. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51164. * @param {BABYLON.Scene} scene is obviously the current scene.
  51165. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51166. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51167. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51168. */
  51169. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51170. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51171. if (invertY === void 0) { invertY = false; }
  51172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51173. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51174. _this._autoLaunch = true;
  51175. var urls = null;
  51176. _this.name = name;
  51177. if (urlsOrVideo instanceof HTMLVideoElement) {
  51178. _this.video = urlsOrVideo;
  51179. }
  51180. else {
  51181. urls = urlsOrVideo;
  51182. _this.video = document.createElement("video");
  51183. _this.video.autoplay = false;
  51184. _this.video.loop = true;
  51185. }
  51186. _this._engine = _this.getScene().getEngine();
  51187. _this._generateMipMaps = generateMipMaps;
  51188. _this._samplingMode = samplingMode;
  51189. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51190. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51191. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51192. }
  51193. else {
  51194. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51195. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51196. _this._generateMipMaps = false;
  51197. }
  51198. if (urls) {
  51199. _this.video.addEventListener("canplay", function () {
  51200. _this._createTexture();
  51201. });
  51202. urls.forEach(function (url) {
  51203. var source = document.createElement("source");
  51204. source.src = url;
  51205. _this.video.appendChild(source);
  51206. });
  51207. }
  51208. else {
  51209. _this._createTexture();
  51210. }
  51211. _this._lastUpdate = BABYLON.Tools.Now;
  51212. return _this;
  51213. }
  51214. VideoTexture.prototype.__setTextureReady = function () {
  51215. if (this._texture) {
  51216. this._texture.isReady = true;
  51217. }
  51218. };
  51219. VideoTexture.prototype._createTexture = function () {
  51220. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51221. if (this._autoLaunch) {
  51222. this._autoLaunch = false;
  51223. this.video.play();
  51224. }
  51225. this._setTextureReady = this.__setTextureReady.bind(this);
  51226. this.video.addEventListener("playing", this._setTextureReady);
  51227. };
  51228. VideoTexture.prototype._rebuild = function () {
  51229. this.update();
  51230. };
  51231. VideoTexture.prototype.update = function () {
  51232. var now = BABYLON.Tools.Now;
  51233. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51234. return false;
  51235. }
  51236. this._lastUpdate = now;
  51237. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51238. return true;
  51239. };
  51240. VideoTexture.prototype.dispose = function () {
  51241. _super.prototype.dispose.call(this);
  51242. this.video.removeEventListener("playing", this._setTextureReady);
  51243. };
  51244. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51245. var video = document.createElement("video");
  51246. var constraintsDeviceId;
  51247. if (constraints && constraints.deviceId) {
  51248. constraintsDeviceId = {
  51249. exact: constraints.deviceId
  51250. };
  51251. }
  51252. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51253. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51254. if (navigator.getUserMedia) {
  51255. navigator.getUserMedia({
  51256. video: {
  51257. deviceId: constraintsDeviceId,
  51258. width: {
  51259. min: (constraints && constraints.minWidth) || 256,
  51260. max: (constraints && constraints.maxWidth) || 640
  51261. },
  51262. height: {
  51263. min: (constraints && constraints.minHeight) || 256,
  51264. max: (constraints && constraints.maxHeight) || 480
  51265. }
  51266. }
  51267. }, function (stream) {
  51268. if (video.mozSrcObject !== undefined) {
  51269. video.mozSrcObject = stream;
  51270. }
  51271. else {
  51272. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51273. }
  51274. video.play();
  51275. if (onReady) {
  51276. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51277. }
  51278. }, function (e) {
  51279. BABYLON.Tools.Error(e.name);
  51280. });
  51281. }
  51282. };
  51283. return VideoTexture;
  51284. }(BABYLON.Texture));
  51285. BABYLON.VideoTexture = VideoTexture;
  51286. })(BABYLON || (BABYLON = {}));
  51287. //# sourceMappingURL=babylon.videoTexture.js.map
  51288. var BABYLON;
  51289. (function (BABYLON) {
  51290. var RawTexture = /** @class */ (function (_super) {
  51291. __extends(RawTexture, _super);
  51292. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51293. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51294. if (invertY === void 0) { invertY = false; }
  51295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51296. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51297. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51298. _this.format = format;
  51299. _this._engine = scene.getEngine();
  51300. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51301. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51302. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51303. return _this;
  51304. }
  51305. RawTexture.prototype.update = function (data) {
  51306. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  51307. };
  51308. // Statics
  51309. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51311. if (invertY === void 0) { invertY = false; }
  51312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51313. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51314. };
  51315. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51316. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51317. if (invertY === void 0) { invertY = false; }
  51318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51319. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51320. };
  51321. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51322. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51323. if (invertY === void 0) { invertY = false; }
  51324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51325. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51326. };
  51327. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51328. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51329. if (invertY === void 0) { invertY = false; }
  51330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51331. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51332. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51333. };
  51334. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51336. if (invertY === void 0) { invertY = false; }
  51337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51338. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51339. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  51340. };
  51341. return RawTexture;
  51342. }(BABYLON.Texture));
  51343. BABYLON.RawTexture = RawTexture;
  51344. })(BABYLON || (BABYLON = {}));
  51345. //# sourceMappingURL=babylon.rawTexture.js.map
  51346. var BABYLON;
  51347. (function (BABYLON) {
  51348. var PostProcess = /** @class */ (function () {
  51349. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51351. if (defines === void 0) { defines = null; }
  51352. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51353. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51354. if (blockCompilation === void 0) { blockCompilation = false; }
  51355. this.name = name;
  51356. this.width = -1;
  51357. this.height = -1;
  51358. this.autoClear = true;
  51359. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51360. this.animations = new Array();
  51361. /*
  51362. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51363. Can only be used on a single postprocess or on the last one of a chain.
  51364. */
  51365. this.enablePixelPerfectMode = false;
  51366. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51367. this.alwaysForcePOT = false;
  51368. this.samples = 1;
  51369. this.adaptScaleToCurrentViewport = false;
  51370. this._reusable = false;
  51371. this._textures = new BABYLON.SmartArray(2);
  51372. this._currentRenderTextureInd = 0;
  51373. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51374. this._texelSize = BABYLON.Vector2.Zero();
  51375. // Events
  51376. /**
  51377. * An event triggered when the postprocess is activated.
  51378. * @type {BABYLON.Observable}
  51379. */
  51380. this.onActivateObservable = new BABYLON.Observable();
  51381. /**
  51382. * An event triggered when the postprocess changes its size.
  51383. * @type {BABYLON.Observable}
  51384. */
  51385. this.onSizeChangedObservable = new BABYLON.Observable();
  51386. /**
  51387. * An event triggered when the postprocess applies its effect.
  51388. * @type {BABYLON.Observable}
  51389. */
  51390. this.onApplyObservable = new BABYLON.Observable();
  51391. /**
  51392. * An event triggered before rendering the postprocess
  51393. * @type {BABYLON.Observable}
  51394. */
  51395. this.onBeforeRenderObservable = new BABYLON.Observable();
  51396. /**
  51397. * An event triggered after rendering the postprocess
  51398. * @type {BABYLON.Observable}
  51399. */
  51400. this.onAfterRenderObservable = new BABYLON.Observable();
  51401. if (camera != null) {
  51402. this._camera = camera;
  51403. this._scene = camera.getScene();
  51404. camera.attachPostProcess(this);
  51405. this._engine = this._scene.getEngine();
  51406. this._scene.postProcesses.push(this);
  51407. }
  51408. else if (engine) {
  51409. this._engine = engine;
  51410. this._engine.postProcesses.push(this);
  51411. }
  51412. this._options = options;
  51413. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51414. this._reusable = reusable || false;
  51415. this._textureType = textureType;
  51416. this._samplers = samplers || [];
  51417. this._samplers.push("textureSampler");
  51418. this._fragmentUrl = fragmentUrl;
  51419. this._vertexUrl = vertexUrl;
  51420. this._parameters = parameters || [];
  51421. this._parameters.push("scale");
  51422. this._indexParameters = indexParameters;
  51423. if (!blockCompilation) {
  51424. this.updateEffect(defines);
  51425. }
  51426. }
  51427. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51428. set: function (callback) {
  51429. if (this._onActivateObserver) {
  51430. this.onActivateObservable.remove(this._onActivateObserver);
  51431. }
  51432. if (callback) {
  51433. this._onActivateObserver = this.onActivateObservable.add(callback);
  51434. }
  51435. },
  51436. enumerable: true,
  51437. configurable: true
  51438. });
  51439. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51440. set: function (callback) {
  51441. if (this._onSizeChangedObserver) {
  51442. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51443. }
  51444. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51445. },
  51446. enumerable: true,
  51447. configurable: true
  51448. });
  51449. Object.defineProperty(PostProcess.prototype, "onApply", {
  51450. set: function (callback) {
  51451. if (this._onApplyObserver) {
  51452. this.onApplyObservable.remove(this._onApplyObserver);
  51453. }
  51454. this._onApplyObserver = this.onApplyObservable.add(callback);
  51455. },
  51456. enumerable: true,
  51457. configurable: true
  51458. });
  51459. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51460. set: function (callback) {
  51461. if (this._onBeforeRenderObserver) {
  51462. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51463. }
  51464. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51470. set: function (callback) {
  51471. if (this._onAfterRenderObserver) {
  51472. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51473. }
  51474. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51475. },
  51476. enumerable: true,
  51477. configurable: true
  51478. });
  51479. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51480. get: function () {
  51481. return this._textures.data[this._currentRenderTextureInd];
  51482. },
  51483. set: function (value) {
  51484. this._forcedOutputTexture = value;
  51485. },
  51486. enumerable: true,
  51487. configurable: true
  51488. });
  51489. PostProcess.prototype.getCamera = function () {
  51490. return this._camera;
  51491. };
  51492. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51493. get: function () {
  51494. if (this._shareOutputWithPostProcess) {
  51495. return this._shareOutputWithPostProcess.texelSize;
  51496. }
  51497. if (this._forcedOutputTexture) {
  51498. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51499. }
  51500. return this._texelSize;
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. PostProcess.prototype.getEngine = function () {
  51506. return this._engine;
  51507. };
  51508. PostProcess.prototype.getEffect = function () {
  51509. return this._effect;
  51510. };
  51511. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51512. this._disposeTextures();
  51513. this._shareOutputWithPostProcess = postProcess;
  51514. return this;
  51515. };
  51516. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51517. if (defines === void 0) { defines = null; }
  51518. if (uniforms === void 0) { uniforms = null; }
  51519. if (samplers === void 0) { samplers = null; }
  51520. 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);
  51521. };
  51522. PostProcess.prototype.isReusable = function () {
  51523. return this._reusable;
  51524. };
  51525. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51526. PostProcess.prototype.markTextureDirty = function () {
  51527. this.width = -1;
  51528. };
  51529. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51530. var _this = this;
  51531. if (sourceTexture === void 0) { sourceTexture = null; }
  51532. camera = camera || this._camera;
  51533. var scene = camera.getScene();
  51534. var engine = scene.getEngine();
  51535. var maxSize = engine.getCaps().maxTextureSize;
  51536. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51537. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51538. var desiredWidth = (this._options.width || requiredWidth);
  51539. var desiredHeight = this._options.height || requiredHeight;
  51540. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51541. if (this.adaptScaleToCurrentViewport) {
  51542. var currentViewport = engine.currentViewport;
  51543. if (currentViewport) {
  51544. desiredWidth *= currentViewport.width;
  51545. desiredHeight *= currentViewport.height;
  51546. }
  51547. }
  51548. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51549. if (!this._options.width) {
  51550. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51551. }
  51552. if (!this._options.height) {
  51553. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51554. }
  51555. }
  51556. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51557. if (this._textures.length > 0) {
  51558. for (var i = 0; i < this._textures.length; i++) {
  51559. this._engine._releaseTexture(this._textures.data[i]);
  51560. }
  51561. this._textures.reset();
  51562. }
  51563. this.width = desiredWidth;
  51564. this.height = desiredHeight;
  51565. var textureSize = { width: this.width, height: this.height };
  51566. var textureOptions = {
  51567. generateMipMaps: false,
  51568. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51569. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51570. samplingMode: this.renderTargetSamplingMode,
  51571. type: this._textureType
  51572. };
  51573. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51574. if (this._reusable) {
  51575. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51576. }
  51577. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51578. this.onSizeChangedObservable.notifyObservers(this);
  51579. }
  51580. this._textures.forEach(function (texture) {
  51581. if (texture.samples !== _this.samples) {
  51582. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51583. }
  51584. });
  51585. }
  51586. var target;
  51587. if (this._shareOutputWithPostProcess) {
  51588. target = this._shareOutputWithPostProcess.outputTexture;
  51589. }
  51590. else if (this._forcedOutputTexture) {
  51591. target = this._forcedOutputTexture;
  51592. this.width = this._forcedOutputTexture.width;
  51593. this.height = this._forcedOutputTexture.height;
  51594. }
  51595. else {
  51596. target = this.outputTexture;
  51597. }
  51598. if (this.enablePixelPerfectMode) {
  51599. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51600. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51601. }
  51602. else {
  51603. this._scaleRatio.copyFromFloats(1, 1);
  51604. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51605. }
  51606. this.onActivateObservable.notifyObservers(camera);
  51607. // Clear
  51608. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51609. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51610. }
  51611. if (this._reusable) {
  51612. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51613. }
  51614. };
  51615. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51616. get: function () {
  51617. return this._effect.isSupported;
  51618. },
  51619. enumerable: true,
  51620. configurable: true
  51621. });
  51622. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51623. get: function () {
  51624. if (this._shareOutputWithPostProcess) {
  51625. return this._shareOutputWithPostProcess.aspectRatio;
  51626. }
  51627. if (this._forcedOutputTexture) {
  51628. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51629. }
  51630. return this.width / this.height;
  51631. },
  51632. enumerable: true,
  51633. configurable: true
  51634. });
  51635. PostProcess.prototype.apply = function () {
  51636. // Check
  51637. if (!this._effect || !this._effect.isReady())
  51638. return null;
  51639. // States
  51640. this._engine.enableEffect(this._effect);
  51641. this._engine.setState(false);
  51642. this._engine.setDepthBuffer(false);
  51643. this._engine.setDepthWrite(false);
  51644. // Alpha
  51645. this._engine.setAlphaMode(this.alphaMode);
  51646. if (this.alphaConstants) {
  51647. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51648. }
  51649. // Texture
  51650. var source;
  51651. if (this._shareOutputWithPostProcess) {
  51652. source = this._shareOutputWithPostProcess.outputTexture;
  51653. }
  51654. else if (this._forcedOutputTexture) {
  51655. source = this._forcedOutputTexture;
  51656. }
  51657. else {
  51658. source = this.outputTexture;
  51659. }
  51660. this._effect._bindTexture("textureSampler", source);
  51661. // Parameters
  51662. this._effect.setVector2("scale", this._scaleRatio);
  51663. this.onApplyObservable.notifyObservers(this._effect);
  51664. return this._effect;
  51665. };
  51666. PostProcess.prototype._disposeTextures = function () {
  51667. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51668. return;
  51669. }
  51670. if (this._textures.length > 0) {
  51671. for (var i = 0; i < this._textures.length; i++) {
  51672. this._engine._releaseTexture(this._textures.data[i]);
  51673. }
  51674. }
  51675. this._textures.dispose();
  51676. };
  51677. PostProcess.prototype.dispose = function (camera) {
  51678. camera = camera || this._camera;
  51679. this._disposeTextures();
  51680. if (this._scene) {
  51681. var index_1 = this._scene.postProcesses.indexOf(this);
  51682. if (index_1 !== -1) {
  51683. this._scene.postProcesses.splice(index_1, 1);
  51684. }
  51685. }
  51686. else {
  51687. var index_2 = this._engine.postProcesses.indexOf(this);
  51688. if (index_2 !== -1) {
  51689. this._engine.postProcesses.splice(index_2, 1);
  51690. }
  51691. }
  51692. if (!camera) {
  51693. return;
  51694. }
  51695. camera.detachPostProcess(this);
  51696. var index = camera._postProcesses.indexOf(this);
  51697. if (index === 0 && camera._postProcesses.length > 0) {
  51698. this._camera._postProcesses[0].markTextureDirty();
  51699. }
  51700. this.onActivateObservable.clear();
  51701. this.onAfterRenderObservable.clear();
  51702. this.onApplyObservable.clear();
  51703. this.onBeforeRenderObservable.clear();
  51704. this.onSizeChangedObservable.clear();
  51705. };
  51706. return PostProcess;
  51707. }());
  51708. BABYLON.PostProcess = PostProcess;
  51709. })(BABYLON || (BABYLON = {}));
  51710. //# sourceMappingURL=babylon.postProcess.js.map
  51711. var BABYLON;
  51712. (function (BABYLON) {
  51713. var PassPostProcess = /** @class */ (function (_super) {
  51714. __extends(PassPostProcess, _super);
  51715. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51716. if (camera === void 0) { camera = null; }
  51717. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51718. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51719. }
  51720. return PassPostProcess;
  51721. }(BABYLON.PostProcess));
  51722. BABYLON.PassPostProcess = PassPostProcess;
  51723. })(BABYLON || (BABYLON = {}));
  51724. //# sourceMappingURL=babylon.passPostProcess.js.map
  51725. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51726. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51727. s = arguments[i];
  51728. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51729. t[p] = s[p];
  51730. }
  51731. return t;
  51732. };
  51733. var BABYLON;
  51734. (function (BABYLON) {
  51735. var ShadowGenerator = /** @class */ (function () {
  51736. /**
  51737. * Creates a ShadowGenerator object.
  51738. * A ShadowGenerator is the required tool to use the shadows.
  51739. * Each light casting shadows needs to use its own ShadowGenerator.
  51740. * Required parameters :
  51741. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51742. * - `light`: the light object generating the shadows.
  51743. * - `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.
  51744. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51745. */
  51746. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51747. // Members
  51748. this._bias = 0.00005;
  51749. this._blurBoxOffset = 1;
  51750. this._blurScale = 2;
  51751. this._blurKernel = 1;
  51752. this._useKernelBlur = false;
  51753. this._filter = ShadowGenerator.FILTER_NONE;
  51754. this._darkness = 0;
  51755. this._transparencyShadow = false;
  51756. /**
  51757. * Controls the extent to which the shadows fade out at the edge of the frustum
  51758. * Used only by directionals and spots
  51759. */
  51760. this.frustumEdgeFalloff = 0;
  51761. this.forceBackFacesOnly = false;
  51762. this._lightDirection = BABYLON.Vector3.Zero();
  51763. this._viewMatrix = BABYLON.Matrix.Zero();
  51764. this._projectionMatrix = BABYLON.Matrix.Zero();
  51765. this._transformMatrix = BABYLON.Matrix.Zero();
  51766. this._currentFaceIndex = 0;
  51767. this._currentFaceIndexCache = 0;
  51768. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51769. this._mapSize = mapSize;
  51770. this._light = light;
  51771. this._scene = light.getScene();
  51772. light._shadowGenerator = this;
  51773. // Texture type fallback from float to int if not supported.
  51774. var caps = this._scene.getEngine().getCaps();
  51775. if (!useFullFloatFirst) {
  51776. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51777. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51778. }
  51779. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51780. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51781. }
  51782. else {
  51783. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51784. }
  51785. }
  51786. else {
  51787. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51788. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51789. }
  51790. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51791. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51792. }
  51793. else {
  51794. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51795. }
  51796. }
  51797. this._initializeGenerator();
  51798. }
  51799. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51800. // Static
  51801. get: function () {
  51802. return ShadowGenerator._FILTER_NONE;
  51803. },
  51804. enumerable: true,
  51805. configurable: true
  51806. });
  51807. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51808. get: function () {
  51809. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51810. },
  51811. enumerable: true,
  51812. configurable: true
  51813. });
  51814. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51815. get: function () {
  51816. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51822. get: function () {
  51823. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51824. },
  51825. enumerable: true,
  51826. configurable: true
  51827. });
  51828. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51829. get: function () {
  51830. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51831. },
  51832. enumerable: true,
  51833. configurable: true
  51834. });
  51835. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51836. get: function () {
  51837. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51843. get: function () {
  51844. return this._bias;
  51845. },
  51846. set: function (bias) {
  51847. this._bias = bias;
  51848. },
  51849. enumerable: true,
  51850. configurable: true
  51851. });
  51852. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51853. get: function () {
  51854. return this._blurBoxOffset;
  51855. },
  51856. set: function (value) {
  51857. if (this._blurBoxOffset === value) {
  51858. return;
  51859. }
  51860. this._blurBoxOffset = value;
  51861. this._disposeBlurPostProcesses();
  51862. },
  51863. enumerable: true,
  51864. configurable: true
  51865. });
  51866. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51867. get: function () {
  51868. return this._blurScale;
  51869. },
  51870. set: function (value) {
  51871. if (this._blurScale === value) {
  51872. return;
  51873. }
  51874. this._blurScale = value;
  51875. this._disposeBlurPostProcesses();
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51881. get: function () {
  51882. return this._blurKernel;
  51883. },
  51884. set: function (value) {
  51885. if (this._blurKernel === value) {
  51886. return;
  51887. }
  51888. this._blurKernel = value;
  51889. this._disposeBlurPostProcesses();
  51890. },
  51891. enumerable: true,
  51892. configurable: true
  51893. });
  51894. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51895. get: function () {
  51896. return this._useKernelBlur;
  51897. },
  51898. set: function (value) {
  51899. if (this._useKernelBlur === value) {
  51900. return;
  51901. }
  51902. this._useKernelBlur = value;
  51903. this._disposeBlurPostProcesses();
  51904. },
  51905. enumerable: true,
  51906. configurable: true
  51907. });
  51908. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51909. get: function () {
  51910. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51911. },
  51912. set: function (value) {
  51913. this._depthScale = value;
  51914. },
  51915. enumerable: true,
  51916. configurable: true
  51917. });
  51918. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51919. get: function () {
  51920. return this._filter;
  51921. },
  51922. set: function (value) {
  51923. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51924. if (this._light.needCube()) {
  51925. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51926. this.useExponentialShadowMap = true;
  51927. return;
  51928. }
  51929. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51930. this.useCloseExponentialShadowMap = true;
  51931. return;
  51932. }
  51933. }
  51934. if (this._filter === value) {
  51935. return;
  51936. }
  51937. this._filter = value;
  51938. this._disposeBlurPostProcesses();
  51939. this._applyFilterValues();
  51940. this._light._markMeshesAsLightDirty();
  51941. },
  51942. enumerable: true,
  51943. configurable: true
  51944. });
  51945. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51946. get: function () {
  51947. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51948. },
  51949. set: function (value) {
  51950. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51951. return;
  51952. }
  51953. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51954. },
  51955. enumerable: true,
  51956. configurable: true
  51957. });
  51958. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51959. get: function () {
  51960. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51961. return this.useExponentialShadowMap;
  51962. },
  51963. set: function (value) {
  51964. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51965. this.useExponentialShadowMap = value;
  51966. },
  51967. enumerable: true,
  51968. configurable: true
  51969. });
  51970. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51971. get: function () {
  51972. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51973. return this.useBlurExponentialShadowMap;
  51974. },
  51975. set: function (value) {
  51976. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51977. this.useBlurExponentialShadowMap = value;
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51983. get: function () {
  51984. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51985. },
  51986. set: function (value) {
  51987. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51988. return;
  51989. }
  51990. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51996. get: function () {
  51997. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51998. },
  51999. set: function (value) {
  52000. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52001. return;
  52002. }
  52003. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52004. },
  52005. enumerable: true,
  52006. configurable: true
  52007. });
  52008. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52009. get: function () {
  52010. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52011. },
  52012. set: function (value) {
  52013. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52014. return;
  52015. }
  52016. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52017. },
  52018. enumerable: true,
  52019. configurable: true
  52020. });
  52021. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52022. get: function () {
  52023. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52024. },
  52025. set: function (value) {
  52026. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52027. return;
  52028. }
  52029. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52030. },
  52031. enumerable: true,
  52032. configurable: true
  52033. });
  52034. /**
  52035. * Returns the darkness value (float).
  52036. */
  52037. ShadowGenerator.prototype.getDarkness = function () {
  52038. return this._darkness;
  52039. };
  52040. /**
  52041. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52042. * Returns the ShadowGenerator.
  52043. */
  52044. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52045. if (darkness >= 1.0)
  52046. this._darkness = 1.0;
  52047. else if (darkness <= 0.0)
  52048. this._darkness = 0.0;
  52049. else
  52050. this._darkness = darkness;
  52051. return this;
  52052. };
  52053. /**
  52054. * Sets the ability to have transparent shadow (boolean).
  52055. * Returns the ShadowGenerator.
  52056. */
  52057. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52058. this._transparencyShadow = hasShadow;
  52059. return this;
  52060. };
  52061. /**
  52062. * Returns a RenderTargetTexture object : the shadow map texture.
  52063. */
  52064. ShadowGenerator.prototype.getShadowMap = function () {
  52065. return this._shadowMap;
  52066. };
  52067. /**
  52068. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52069. */
  52070. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52071. if (this._shadowMap2) {
  52072. return this._shadowMap2;
  52073. }
  52074. return this._shadowMap;
  52075. };
  52076. /**
  52077. * Helper function to add a mesh and its descendants to the list of shadow casters
  52078. * @param mesh Mesh to add
  52079. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52080. */
  52081. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52082. if (includeDescendants === void 0) { includeDescendants = true; }
  52083. if (!this._shadowMap) {
  52084. return this;
  52085. }
  52086. if (!this._shadowMap.renderList) {
  52087. this._shadowMap.renderList = [];
  52088. }
  52089. this._shadowMap.renderList.push(mesh);
  52090. if (includeDescendants) {
  52091. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52092. }
  52093. return this;
  52094. var _a;
  52095. };
  52096. /**
  52097. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52098. * @param mesh Mesh to remove
  52099. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52100. */
  52101. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52102. if (includeDescendants === void 0) { includeDescendants = true; }
  52103. if (!this._shadowMap || !this._shadowMap.renderList) {
  52104. return this;
  52105. }
  52106. var index = this._shadowMap.renderList.indexOf(mesh);
  52107. if (index !== -1) {
  52108. this._shadowMap.renderList.splice(index, 1);
  52109. }
  52110. if (includeDescendants) {
  52111. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52112. var child = _a[_i];
  52113. this.removeShadowCaster(child);
  52114. }
  52115. }
  52116. return this;
  52117. };
  52118. /**
  52119. * Returns the associated light object.
  52120. */
  52121. ShadowGenerator.prototype.getLight = function () {
  52122. return this._light;
  52123. };
  52124. ShadowGenerator.prototype._initializeGenerator = function () {
  52125. this._light._markMeshesAsLightDirty();
  52126. this._initializeShadowMap();
  52127. };
  52128. ShadowGenerator.prototype._initializeShadowMap = function () {
  52129. var _this = this;
  52130. // Render target
  52131. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52132. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52133. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52134. this._shadowMap.anisotropicFilteringLevel = 1;
  52135. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52136. this._shadowMap.renderParticles = false;
  52137. this._shadowMap.ignoreCameraViewport = true;
  52138. // Record Face Index before render.
  52139. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52140. _this._currentFaceIndex = faceIndex;
  52141. });
  52142. // Custom render function.
  52143. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52144. // Blur if required afer render.
  52145. this._shadowMap.onAfterUnbindObservable.add(function () {
  52146. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52147. return;
  52148. }
  52149. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52150. _this._initializeBlurRTTAndPostProcesses();
  52151. }
  52152. var shadowMap = _this.getShadowMapForRendering();
  52153. if (shadowMap) {
  52154. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52155. }
  52156. });
  52157. // Clear according to the chosen filter.
  52158. this._shadowMap.onClearObservable.add(function (engine) {
  52159. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52160. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52161. }
  52162. else {
  52163. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52164. }
  52165. });
  52166. };
  52167. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52168. var _this = this;
  52169. var engine = this._scene.getEngine();
  52170. var targetSize = this._mapSize / this.blurScale;
  52171. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52172. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52173. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52174. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52175. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52176. }
  52177. if (this.useKernelBlur) {
  52178. 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);
  52179. this._kernelBlurXPostprocess.width = targetSize;
  52180. this._kernelBlurXPostprocess.height = targetSize;
  52181. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52182. effect.setTexture("textureSampler", _this._shadowMap);
  52183. });
  52184. 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);
  52185. this._kernelBlurXPostprocess.autoClear = false;
  52186. this._kernelBlurYPostprocess.autoClear = false;
  52187. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52188. this._kernelBlurXPostprocess.packedFloat = true;
  52189. this._kernelBlurYPostprocess.packedFloat = true;
  52190. }
  52191. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52192. }
  52193. else {
  52194. 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);
  52195. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52196. effect.setFloat2("screenSize", targetSize, targetSize);
  52197. effect.setTexture("textureSampler", _this._shadowMap);
  52198. });
  52199. this._boxBlurPostprocess.autoClear = false;
  52200. this._blurPostProcesses = [this._boxBlurPostprocess];
  52201. }
  52202. };
  52203. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52204. var index;
  52205. var engine = this._scene.getEngine();
  52206. if (depthOnlySubMeshes.length) {
  52207. engine.setColorWrite(false);
  52208. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52209. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52210. }
  52211. engine.setColorWrite(true);
  52212. }
  52213. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52214. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52215. }
  52216. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52217. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52218. }
  52219. if (this._transparencyShadow) {
  52220. for (index = 0; index < transparentSubMeshes.length; index++) {
  52221. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52222. }
  52223. }
  52224. };
  52225. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52226. var _this = this;
  52227. var mesh = subMesh.getRenderingMesh();
  52228. var scene = this._scene;
  52229. var engine = scene.getEngine();
  52230. var material = subMesh.getMaterial();
  52231. if (!material) {
  52232. return;
  52233. }
  52234. // Culling
  52235. engine.setState(material.backFaceCulling);
  52236. // Managing instances
  52237. var batch = mesh._getInstancesRenderList(subMesh._id);
  52238. if (batch.mustReturn) {
  52239. return;
  52240. }
  52241. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52242. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52243. engine.enableEffect(this._effect);
  52244. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52245. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52246. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52247. this._effect.setVector3("lightPosition", this.getLight().position);
  52248. if (scene.activeCamera) {
  52249. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52250. }
  52251. // Alpha test
  52252. if (material && material.needAlphaTesting()) {
  52253. var alphaTexture = material.getAlphaTestTexture();
  52254. if (alphaTexture) {
  52255. this._effect.setTexture("diffuseSampler", alphaTexture);
  52256. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52257. }
  52258. }
  52259. // Bones
  52260. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52261. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52262. }
  52263. if (this.forceBackFacesOnly) {
  52264. engine.setState(true, 0, false, true);
  52265. }
  52266. // Draw
  52267. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52268. if (this.forceBackFacesOnly) {
  52269. engine.setState(true, 0, false, false);
  52270. }
  52271. }
  52272. else {
  52273. // Need to reset refresh rate of the shadowMap
  52274. if (this._shadowMap) {
  52275. this._shadowMap.resetRefreshCounter();
  52276. }
  52277. }
  52278. };
  52279. ShadowGenerator.prototype._applyFilterValues = function () {
  52280. if (!this._shadowMap) {
  52281. return;
  52282. }
  52283. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52284. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52285. }
  52286. else {
  52287. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52288. }
  52289. };
  52290. /**
  52291. * Force shader compilation including textures ready check
  52292. */
  52293. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52294. var _this = this;
  52295. var localOptions = __assign({ useInstances: false }, options);
  52296. var shadowMap = this.getShadowMap();
  52297. if (!shadowMap) {
  52298. if (onCompiled) {
  52299. onCompiled(this);
  52300. }
  52301. return;
  52302. }
  52303. var renderList = shadowMap.renderList;
  52304. if (!renderList) {
  52305. if (onCompiled) {
  52306. onCompiled(this);
  52307. }
  52308. return;
  52309. }
  52310. var subMeshes = new Array();
  52311. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52312. var mesh = renderList_1[_i];
  52313. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52314. }
  52315. if (subMeshes.length === 0) {
  52316. if (onCompiled) {
  52317. onCompiled(this);
  52318. }
  52319. return;
  52320. }
  52321. var currentIndex = 0;
  52322. var checkReady = function () {
  52323. if (!_this._scene || !_this._scene.getEngine()) {
  52324. return;
  52325. }
  52326. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52327. currentIndex++;
  52328. if (currentIndex >= subMeshes.length) {
  52329. if (onCompiled) {
  52330. onCompiled(_this);
  52331. }
  52332. return;
  52333. }
  52334. }
  52335. setTimeout(checkReady, 16);
  52336. };
  52337. checkReady();
  52338. };
  52339. /**
  52340. * Boolean : true when the ShadowGenerator is finally computed.
  52341. */
  52342. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52343. var defines = [];
  52344. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52345. defines.push("#define FLOAT");
  52346. }
  52347. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52348. defines.push("#define ESM");
  52349. }
  52350. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52351. var mesh = subMesh.getMesh();
  52352. var material = subMesh.getMaterial();
  52353. // Alpha test
  52354. if (material && material.needAlphaTesting()) {
  52355. var alphaTexture = material.getAlphaTestTexture();
  52356. if (alphaTexture) {
  52357. defines.push("#define ALPHATEST");
  52358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52359. attribs.push(BABYLON.VertexBuffer.UVKind);
  52360. defines.push("#define UV1");
  52361. }
  52362. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52363. if (alphaTexture.coordinatesIndex === 1) {
  52364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52365. defines.push("#define UV2");
  52366. }
  52367. }
  52368. }
  52369. }
  52370. // Bones
  52371. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52372. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52373. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52374. if (mesh.numBoneInfluencers > 4) {
  52375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52377. }
  52378. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52379. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52380. }
  52381. else {
  52382. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52383. }
  52384. // Instances
  52385. if (useInstances) {
  52386. defines.push("#define INSTANCES");
  52387. attribs.push("world0");
  52388. attribs.push("world1");
  52389. attribs.push("world2");
  52390. attribs.push("world3");
  52391. }
  52392. // Get correct effect
  52393. var join = defines.join("\n");
  52394. if (this._cachedDefines !== join) {
  52395. this._cachedDefines = join;
  52396. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52397. }
  52398. return this._effect.isReady();
  52399. };
  52400. /**
  52401. * This creates the defines related to the standard BJS materials.
  52402. */
  52403. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52404. var scene = this._scene;
  52405. var light = this._light;
  52406. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52407. return;
  52408. }
  52409. defines["SHADOW" + lightIndex] = true;
  52410. if (this.usePoissonSampling) {
  52411. defines["SHADOWPCF" + lightIndex] = true;
  52412. }
  52413. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52414. defines["SHADOWESM" + lightIndex] = true;
  52415. }
  52416. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52417. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52418. }
  52419. if (light.needCube()) {
  52420. defines["SHADOWCUBE" + lightIndex] = true;
  52421. }
  52422. };
  52423. /**
  52424. * This binds shadow lights related to the standard BJS materials.
  52425. * It implies the unifroms available on the materials are the standard BJS ones.
  52426. */
  52427. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52428. var light = this._light;
  52429. var scene = this._scene;
  52430. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52431. return;
  52432. }
  52433. var camera = scene.activeCamera;
  52434. if (!camera) {
  52435. return;
  52436. }
  52437. var shadowMap = this.getShadowMap();
  52438. if (!shadowMap) {
  52439. return;
  52440. }
  52441. if (!light.needCube()) {
  52442. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52443. }
  52444. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52445. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52446. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52447. };
  52448. // Methods
  52449. /**
  52450. * Returns a Matrix object : the updated transformation matrix.
  52451. */
  52452. ShadowGenerator.prototype.getTransformMatrix = function () {
  52453. var scene = this._scene;
  52454. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52455. return this._transformMatrix;
  52456. }
  52457. this._currentRenderID = scene.getRenderId();
  52458. this._currentFaceIndexCache = this._currentFaceIndex;
  52459. var lightPosition = this._light.position;
  52460. if (this._light.computeTransformedInformation()) {
  52461. lightPosition = this._light.transformedPosition;
  52462. }
  52463. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52464. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52465. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52466. }
  52467. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52468. this._cachedPosition = lightPosition.clone();
  52469. this._cachedDirection = this._lightDirection.clone();
  52470. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52471. var shadowMap = this.getShadowMap();
  52472. if (shadowMap) {
  52473. var renderList = shadowMap.renderList;
  52474. if (renderList) {
  52475. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52476. }
  52477. }
  52478. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52479. }
  52480. return this._transformMatrix;
  52481. };
  52482. ShadowGenerator.prototype.recreateShadowMap = function () {
  52483. var shadowMap = this._shadowMap;
  52484. if (!shadowMap) {
  52485. return;
  52486. }
  52487. // Track render list.
  52488. var renderList = shadowMap.renderList;
  52489. // Clean up existing data.
  52490. this._disposeRTTandPostProcesses();
  52491. // Reinitializes.
  52492. this._initializeGenerator();
  52493. // Reaffect the filter to ensure a correct fallback if necessary.
  52494. this.filter = this.filter;
  52495. // Reaffect the filter.
  52496. this._applyFilterValues();
  52497. // Reaffect Render List.
  52498. this._shadowMap.renderList = renderList;
  52499. };
  52500. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52501. if (this._shadowMap2) {
  52502. this._shadowMap2.dispose();
  52503. this._shadowMap2 = null;
  52504. }
  52505. if (this._downSamplePostprocess) {
  52506. this._downSamplePostprocess.dispose();
  52507. this._downSamplePostprocess = null;
  52508. }
  52509. if (this._boxBlurPostprocess) {
  52510. this._boxBlurPostprocess.dispose();
  52511. this._boxBlurPostprocess = null;
  52512. }
  52513. if (this._kernelBlurXPostprocess) {
  52514. this._kernelBlurXPostprocess.dispose();
  52515. this._kernelBlurXPostprocess = null;
  52516. }
  52517. if (this._kernelBlurYPostprocess) {
  52518. this._kernelBlurYPostprocess.dispose();
  52519. this._kernelBlurYPostprocess = null;
  52520. }
  52521. this._blurPostProcesses = [];
  52522. };
  52523. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52524. if (this._shadowMap) {
  52525. this._shadowMap.dispose();
  52526. this._shadowMap = null;
  52527. }
  52528. this._disposeBlurPostProcesses();
  52529. };
  52530. /**
  52531. * Disposes the ShadowGenerator.
  52532. * Returns nothing.
  52533. */
  52534. ShadowGenerator.prototype.dispose = function () {
  52535. this._disposeRTTandPostProcesses();
  52536. if (this._light) {
  52537. this._light._shadowGenerator = null;
  52538. this._light._markMeshesAsLightDirty();
  52539. }
  52540. };
  52541. /**
  52542. * Serializes the ShadowGenerator and returns a serializationObject.
  52543. */
  52544. ShadowGenerator.prototype.serialize = function () {
  52545. var serializationObject = {};
  52546. var shadowMap = this.getShadowMap();
  52547. if (!shadowMap) {
  52548. return serializationObject;
  52549. }
  52550. serializationObject.lightId = this._light.id;
  52551. serializationObject.mapSize = shadowMap.getRenderSize();
  52552. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52553. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52554. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52555. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52556. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52557. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52558. serializationObject.depthScale = this.depthScale;
  52559. serializationObject.darkness = this.getDarkness();
  52560. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52561. serializationObject.blurKernel = this.blurKernel;
  52562. serializationObject.blurScale = this.blurScale;
  52563. serializationObject.useKernelBlur = this.useKernelBlur;
  52564. serializationObject.transparencyShadow = this._transparencyShadow;
  52565. serializationObject.renderList = [];
  52566. if (shadowMap.renderList) {
  52567. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52568. var mesh = shadowMap.renderList[meshIndex];
  52569. serializationObject.renderList.push(mesh.id);
  52570. }
  52571. }
  52572. return serializationObject;
  52573. };
  52574. /**
  52575. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52576. */
  52577. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52578. //casting to point light, as light is missing the position attr and typescript complains.
  52579. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52580. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52581. var shadowMap = shadowGenerator.getShadowMap();
  52582. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52583. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52584. meshes.forEach(function (mesh) {
  52585. if (!shadowMap) {
  52586. return;
  52587. }
  52588. if (!shadowMap.renderList) {
  52589. shadowMap.renderList = [];
  52590. }
  52591. shadowMap.renderList.push(mesh);
  52592. });
  52593. }
  52594. if (parsedShadowGenerator.usePoissonSampling) {
  52595. shadowGenerator.usePoissonSampling = true;
  52596. }
  52597. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52598. shadowGenerator.useExponentialShadowMap = true;
  52599. }
  52600. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52601. shadowGenerator.useBlurExponentialShadowMap = true;
  52602. }
  52603. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52604. shadowGenerator.useCloseExponentialShadowMap = true;
  52605. }
  52606. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52607. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52608. }
  52609. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52610. shadowGenerator.useExponentialShadowMap = true;
  52611. }
  52612. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52613. shadowGenerator.useBlurExponentialShadowMap = true;
  52614. }
  52615. if (parsedShadowGenerator.depthScale) {
  52616. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52617. }
  52618. if (parsedShadowGenerator.blurScale) {
  52619. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52620. }
  52621. if (parsedShadowGenerator.blurBoxOffset) {
  52622. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52623. }
  52624. if (parsedShadowGenerator.useKernelBlur) {
  52625. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52626. }
  52627. if (parsedShadowGenerator.blurKernel) {
  52628. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52629. }
  52630. if (parsedShadowGenerator.bias !== undefined) {
  52631. shadowGenerator.bias = parsedShadowGenerator.bias;
  52632. }
  52633. if (parsedShadowGenerator.darkness) {
  52634. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52635. }
  52636. if (parsedShadowGenerator.transparencyShadow) {
  52637. shadowGenerator.setTransparencyShadow(true);
  52638. }
  52639. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52640. return shadowGenerator;
  52641. };
  52642. ShadowGenerator._FILTER_NONE = 0;
  52643. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52644. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52645. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52646. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52647. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52648. return ShadowGenerator;
  52649. }());
  52650. BABYLON.ShadowGenerator = ShadowGenerator;
  52651. })(BABYLON || (BABYLON = {}));
  52652. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52653. var BABYLON;
  52654. (function (BABYLON) {
  52655. var DefaultLoadingScreen = /** @class */ (function () {
  52656. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52657. if (_loadingText === void 0) { _loadingText = ""; }
  52658. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52659. var _this = this;
  52660. this._renderingCanvas = _renderingCanvas;
  52661. this._loadingText = _loadingText;
  52662. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52663. // Resize
  52664. this._resizeLoadingUI = function () {
  52665. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52666. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52667. if (!_this._loadingDiv) {
  52668. return;
  52669. }
  52670. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52671. _this._loadingDiv.style.left = canvasRect.left + "px";
  52672. _this._loadingDiv.style.top = canvasRect.top + "px";
  52673. _this._loadingDiv.style.width = canvasRect.width + "px";
  52674. _this._loadingDiv.style.height = canvasRect.height + "px";
  52675. };
  52676. }
  52677. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52678. if (this._loadingDiv) {
  52679. // Do not add a loading screen if there is already one
  52680. return;
  52681. }
  52682. this._loadingDiv = document.createElement("div");
  52683. this._loadingDiv.id = "babylonjsLoadingDiv";
  52684. this._loadingDiv.style.opacity = "0";
  52685. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52686. this._loadingDiv.style.pointerEvents = "none";
  52687. // Loading text
  52688. this._loadingTextDiv = document.createElement("div");
  52689. this._loadingTextDiv.style.position = "absolute";
  52690. this._loadingTextDiv.style.left = "0";
  52691. this._loadingTextDiv.style.top = "50%";
  52692. this._loadingTextDiv.style.marginTop = "80px";
  52693. this._loadingTextDiv.style.width = "100%";
  52694. this._loadingTextDiv.style.height = "20px";
  52695. this._loadingTextDiv.style.fontFamily = "Arial";
  52696. this._loadingTextDiv.style.fontSize = "14px";
  52697. this._loadingTextDiv.style.color = "white";
  52698. this._loadingTextDiv.style.textAlign = "center";
  52699. this._loadingTextDiv.innerHTML = "Loading";
  52700. this._loadingDiv.appendChild(this._loadingTextDiv);
  52701. //set the predefined text
  52702. this._loadingTextDiv.innerHTML = this._loadingText;
  52703. // Generating keyframes
  52704. var style = document.createElement('style');
  52705. style.type = 'text/css';
  52706. 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 }";
  52707. style.innerHTML = keyFrames;
  52708. document.getElementsByTagName('head')[0].appendChild(style);
  52709. // Loading img
  52710. var imgBack = new Image();
  52711. 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";
  52712. imgBack.style.position = "absolute";
  52713. imgBack.style.left = "50%";
  52714. imgBack.style.top = "50%";
  52715. imgBack.style.marginLeft = "-60px";
  52716. imgBack.style.marginTop = "-60px";
  52717. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52718. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52719. imgBack.style.transformOrigin = "50% 50%";
  52720. imgBack.style.webkitTransformOrigin = "50% 50%";
  52721. this._loadingDiv.appendChild(imgBack);
  52722. this._resizeLoadingUI();
  52723. window.addEventListener("resize", this._resizeLoadingUI);
  52724. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52725. document.body.appendChild(this._loadingDiv);
  52726. this._loadingDiv.style.opacity = "1";
  52727. };
  52728. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52729. var _this = this;
  52730. if (!this._loadingDiv) {
  52731. return;
  52732. }
  52733. var onTransitionEnd = function () {
  52734. if (!_this._loadingDiv) {
  52735. return;
  52736. }
  52737. document.body.removeChild(_this._loadingDiv);
  52738. window.removeEventListener("resize", _this._resizeLoadingUI);
  52739. _this._loadingDiv = null;
  52740. };
  52741. this._loadingDiv.style.opacity = "0";
  52742. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52743. };
  52744. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52745. set: function (text) {
  52746. this._loadingText = text;
  52747. if (this._loadingTextDiv) {
  52748. this._loadingTextDiv.innerHTML = this._loadingText;
  52749. }
  52750. },
  52751. enumerable: true,
  52752. configurable: true
  52753. });
  52754. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52755. get: function () {
  52756. return this._loadingDivBackgroundColor;
  52757. },
  52758. set: function (color) {
  52759. this._loadingDivBackgroundColor = color;
  52760. if (!this._loadingDiv) {
  52761. return;
  52762. }
  52763. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52764. },
  52765. enumerable: true,
  52766. configurable: true
  52767. });
  52768. return DefaultLoadingScreen;
  52769. }());
  52770. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52771. })(BABYLON || (BABYLON = {}));
  52772. //# sourceMappingURL=babylon.loadingScreen.js.map
  52773. var BABYLON;
  52774. (function (BABYLON) {
  52775. var SceneLoader = /** @class */ (function () {
  52776. function SceneLoader() {
  52777. }
  52778. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52779. get: function () {
  52780. return 0;
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52786. get: function () {
  52787. return 1;
  52788. },
  52789. enumerable: true,
  52790. configurable: true
  52791. });
  52792. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52793. get: function () {
  52794. return 2;
  52795. },
  52796. enumerable: true,
  52797. configurable: true
  52798. });
  52799. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52800. get: function () {
  52801. return 3;
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52807. get: function () {
  52808. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52809. },
  52810. set: function (value) {
  52811. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52812. },
  52813. enumerable: true,
  52814. configurable: true
  52815. });
  52816. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52817. get: function () {
  52818. return SceneLoader._ShowLoadingScreen;
  52819. },
  52820. set: function (value) {
  52821. SceneLoader._ShowLoadingScreen = value;
  52822. },
  52823. enumerable: true,
  52824. configurable: true
  52825. });
  52826. Object.defineProperty(SceneLoader, "loggingLevel", {
  52827. get: function () {
  52828. return SceneLoader._loggingLevel;
  52829. },
  52830. set: function (value) {
  52831. SceneLoader._loggingLevel = value;
  52832. },
  52833. enumerable: true,
  52834. configurable: true
  52835. });
  52836. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52837. get: function () {
  52838. return SceneLoader._CleanBoneMatrixWeights;
  52839. },
  52840. set: function (value) {
  52841. SceneLoader._CleanBoneMatrixWeights = value;
  52842. },
  52843. enumerable: true,
  52844. configurable: true
  52845. });
  52846. SceneLoader._getDefaultPlugin = function () {
  52847. return SceneLoader._registeredPlugins[".babylon"];
  52848. };
  52849. SceneLoader._getPluginForExtension = function (extension) {
  52850. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52851. if (registeredPlugin) {
  52852. return registeredPlugin;
  52853. }
  52854. return SceneLoader._getDefaultPlugin();
  52855. };
  52856. SceneLoader._getPluginForDirectLoad = function (data) {
  52857. for (var extension in SceneLoader._registeredPlugins) {
  52858. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52859. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52860. return SceneLoader._registeredPlugins[extension];
  52861. }
  52862. }
  52863. return SceneLoader._getDefaultPlugin();
  52864. };
  52865. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52866. if (sceneFilename.name) {
  52867. sceneFilename = sceneFilename.name;
  52868. }
  52869. var queryStringPosition = sceneFilename.indexOf("?");
  52870. if (queryStringPosition !== -1) {
  52871. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  52872. }
  52873. var dotPosition = sceneFilename.lastIndexOf(".");
  52874. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  52875. return SceneLoader._getPluginForExtension(extension);
  52876. };
  52877. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52878. SceneLoader._getDirectLoad = function (sceneFilename) {
  52879. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52880. return sceneFilename.substr(5);
  52881. }
  52882. return null;
  52883. };
  52884. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52885. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52886. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52887. var plugin;
  52888. if (registeredPlugin.plugin.createPlugin) {
  52889. plugin = registeredPlugin.plugin.createPlugin();
  52890. }
  52891. else {
  52892. plugin = registeredPlugin.plugin;
  52893. }
  52894. var useArrayBuffer = registeredPlugin.isBinary;
  52895. var database;
  52896. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  52897. var dataCallback = function (data, responseURL) {
  52898. if (scene.isDisposed) {
  52899. onError("Scene has been disposed");
  52900. return;
  52901. }
  52902. scene.database = database;
  52903. try {
  52904. onSuccess(plugin, data, responseURL);
  52905. }
  52906. catch (e) {
  52907. onError(null, e);
  52908. }
  52909. };
  52910. var manifestChecked = function (success) {
  52911. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52912. if (request) {
  52913. onError(request.status + " " + request.statusText);
  52914. }
  52915. });
  52916. };
  52917. if (directLoad) {
  52918. dataCallback(directLoad);
  52919. return plugin;
  52920. }
  52921. if (rootUrl.indexOf("file:") === -1) {
  52922. if (scene.getEngine().enableOfflineSupport) {
  52923. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52924. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52925. }
  52926. else {
  52927. manifestChecked(true);
  52928. }
  52929. }
  52930. else {
  52931. var fileOrString = sceneFilename;
  52932. if (fileOrString.name) {
  52933. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52934. }
  52935. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52936. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52937. }
  52938. else {
  52939. onError("Unable to find file named " + sceneFilename);
  52940. }
  52941. }
  52942. return plugin;
  52943. };
  52944. // Public functions
  52945. SceneLoader.GetPluginForExtension = function (extension) {
  52946. return SceneLoader._getPluginForExtension(extension).plugin;
  52947. };
  52948. SceneLoader.RegisterPlugin = function (plugin) {
  52949. if (typeof plugin.extensions === "string") {
  52950. var extension = plugin.extensions;
  52951. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52952. plugin: plugin,
  52953. isBinary: false
  52954. };
  52955. }
  52956. else {
  52957. var extensions = plugin.extensions;
  52958. Object.keys(extensions).forEach(function (extension) {
  52959. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52960. plugin: plugin,
  52961. isBinary: extensions[extension].isBinary
  52962. };
  52963. });
  52964. }
  52965. };
  52966. /**
  52967. * Import meshes into a scene
  52968. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52969. * @param rootUrl a string that defines the root url for scene and resources
  52970. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52971. * @param scene the instance of BABYLON.Scene to append to
  52972. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52973. * @param onProgress a callback with a progress event for each file being loaded
  52974. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52975. */
  52976. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52977. if (onSuccess === void 0) { onSuccess = null; }
  52978. if (onProgress === void 0) { onProgress = null; }
  52979. if (onError === void 0) { onError = null; }
  52980. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52981. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52982. return null;
  52983. }
  52984. var loadingToken = {};
  52985. scene._addPendingData(loadingToken);
  52986. var errorHandler = function (message, exception) {
  52987. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52988. if (onError) {
  52989. onError(scene, errorMessage, exception);
  52990. }
  52991. else {
  52992. BABYLON.Tools.Error(errorMessage);
  52993. // should the exception be thrown?
  52994. }
  52995. scene._removePendingData(loadingToken);
  52996. };
  52997. var progressHandler = function (event) {
  52998. if (onProgress) {
  52999. onProgress(event);
  53000. }
  53001. };
  53002. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53003. if (plugin.rewriteRootURL) {
  53004. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53005. }
  53006. if (plugin.importMesh) {
  53007. var syncedPlugin = plugin;
  53008. var meshes = new Array();
  53009. var particleSystems = new Array();
  53010. var skeletons = new Array();
  53011. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53012. return;
  53013. }
  53014. if (onSuccess) {
  53015. // wrap onSuccess with try-catch to know if something went wrong.
  53016. try {
  53017. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53018. onSuccess(meshes, particleSystems, skeletons);
  53019. scene._removePendingData(loadingToken);
  53020. }
  53021. catch (e) {
  53022. var message = 'Error in onSuccess callback.';
  53023. errorHandler(message, e);
  53024. }
  53025. }
  53026. }
  53027. else {
  53028. var asyncedPlugin = plugin;
  53029. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53030. if (onSuccess) {
  53031. try {
  53032. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53033. onSuccess(meshes, particleSystems, skeletons);
  53034. scene._removePendingData(loadingToken);
  53035. }
  53036. catch (e) {
  53037. var message = 'Error in onSuccess callback.';
  53038. errorHandler(message, e);
  53039. }
  53040. }
  53041. }, progressHandler, errorHandler);
  53042. }
  53043. }, progressHandler, errorHandler, pluginExtension);
  53044. };
  53045. /**
  53046. * Load a scene
  53047. * @param rootUrl a string that defines the root url for scene and resources
  53048. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53049. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53050. * @param onSuccess a callback with the scene when import succeeds
  53051. * @param onProgress a callback with a progress event for each file being loaded
  53052. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53053. */
  53054. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53055. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53056. };
  53057. /**
  53058. * Append a scene
  53059. * @param rootUrl a string that defines the root url for scene and resources
  53060. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53061. * @param scene is the instance of BABYLON.Scene to append to
  53062. * @param onSuccess a callback with the scene when import succeeds
  53063. * @param onProgress a callback with a progress event for each file being loaded
  53064. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53065. */
  53066. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53067. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53068. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53069. return null;
  53070. }
  53071. if (SceneLoader.ShowLoadingScreen) {
  53072. scene.getEngine().displayLoadingUI();
  53073. }
  53074. var loadingToken = {};
  53075. scene._addPendingData(loadingToken);
  53076. var errorHandler = function (message, exception) {
  53077. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53078. if (onError) {
  53079. onError(scene, errorMessage, exception);
  53080. }
  53081. else {
  53082. BABYLON.Tools.Error(errorMessage);
  53083. // should the exception be thrown?
  53084. }
  53085. scene._removePendingData(loadingToken);
  53086. scene.getEngine().hideLoadingUI();
  53087. };
  53088. var progressHandler = function (event) {
  53089. if (onProgress) {
  53090. onProgress(event);
  53091. }
  53092. };
  53093. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53094. if (plugin.load) {
  53095. var syncedPlugin = plugin;
  53096. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53097. return;
  53098. }
  53099. if (onSuccess) {
  53100. try {
  53101. onSuccess(scene);
  53102. }
  53103. catch (e) {
  53104. errorHandler("Error in onSuccess callback", e);
  53105. }
  53106. }
  53107. scene.loadingPluginName = plugin.name;
  53108. scene._removePendingData(loadingToken);
  53109. }
  53110. else {
  53111. var asyncedPlugin = plugin;
  53112. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53113. if (onSuccess) {
  53114. onSuccess(scene);
  53115. }
  53116. scene.loadingPluginName = plugin.name;
  53117. scene._removePendingData(loadingToken);
  53118. }, progressHandler, errorHandler);
  53119. }
  53120. if (SceneLoader.ShowLoadingScreen) {
  53121. scene.executeWhenReady(function () {
  53122. scene.getEngine().hideLoadingUI();
  53123. });
  53124. }
  53125. }, progressHandler, errorHandler, pluginExtension);
  53126. };
  53127. // Flags
  53128. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53129. SceneLoader._ShowLoadingScreen = true;
  53130. SceneLoader._CleanBoneMatrixWeights = false;
  53131. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53132. // Members
  53133. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53134. SceneLoader._registeredPlugins = {};
  53135. return SceneLoader;
  53136. }());
  53137. BABYLON.SceneLoader = SceneLoader;
  53138. ;
  53139. })(BABYLON || (BABYLON = {}));
  53140. //# sourceMappingURL=babylon.sceneLoader.js.map
  53141. var BABYLON;
  53142. (function (BABYLON) {
  53143. var Internals;
  53144. (function (Internals) {
  53145. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53146. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53147. var parsedMaterial = parsedData.materials[index];
  53148. if (parsedMaterial.id === id) {
  53149. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53150. }
  53151. }
  53152. return null;
  53153. };
  53154. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53155. for (var i in names) {
  53156. if (mesh.name === names[i]) {
  53157. hierarchyIds.push(mesh.id);
  53158. return true;
  53159. }
  53160. }
  53161. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53162. hierarchyIds.push(mesh.id);
  53163. return true;
  53164. }
  53165. return false;
  53166. };
  53167. var logOperation = function (operation, producer) {
  53168. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53169. };
  53170. BABYLON.SceneLoader.RegisterPlugin({
  53171. name: "babylon.js",
  53172. extensions: ".babylon",
  53173. canDirectLoad: function (data) {
  53174. if (data.indexOf("babylon") !== -1) {
  53175. return true;
  53176. }
  53177. return false;
  53178. },
  53179. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53180. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53181. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53182. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53183. // and avoid problems with multiple concurrent .babylon loads.
  53184. var log = "importMesh has failed JSON parse";
  53185. try {
  53186. var parsedData = JSON.parse(data);
  53187. log = "";
  53188. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53189. if (!meshesNames) {
  53190. meshesNames = null;
  53191. }
  53192. else if (!Array.isArray(meshesNames)) {
  53193. meshesNames = [meshesNames];
  53194. }
  53195. var hierarchyIds = new Array();
  53196. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53197. var loadedSkeletonsIds = [];
  53198. var loadedMaterialsIds = [];
  53199. var index;
  53200. var cache;
  53201. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53202. var parsedMesh = parsedData.meshes[index];
  53203. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53204. if (meshesNames !== null) {
  53205. // Remove found mesh name from list.
  53206. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53207. }
  53208. //Geometry?
  53209. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53210. //does the file contain geometries?
  53211. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53212. //find the correct geometry and add it to the scene
  53213. var found = false;
  53214. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53215. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53216. return;
  53217. }
  53218. else {
  53219. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53220. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53221. switch (geometryType) {
  53222. case "boxes":
  53223. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53224. break;
  53225. case "spheres":
  53226. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53227. break;
  53228. case "cylinders":
  53229. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53230. break;
  53231. case "toruses":
  53232. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53233. break;
  53234. case "grounds":
  53235. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53236. break;
  53237. case "planes":
  53238. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53239. break;
  53240. case "torusKnots":
  53241. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53242. break;
  53243. case "vertexData":
  53244. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53245. break;
  53246. }
  53247. found = true;
  53248. }
  53249. });
  53250. }
  53251. });
  53252. if (found === false) {
  53253. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53254. }
  53255. }
  53256. }
  53257. // Material ?
  53258. if (parsedMesh.materialId) {
  53259. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53260. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53261. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53262. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53263. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53264. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53265. var subMatId = parsedMultiMaterial.materials[matIndex];
  53266. loadedMaterialsIds.push(subMatId);
  53267. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53268. log += "\n\tMaterial " + mat.toString(fullDetails);
  53269. }
  53270. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53271. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53272. materialFound = true;
  53273. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53274. break;
  53275. }
  53276. }
  53277. }
  53278. if (materialFound === false) {
  53279. loadedMaterialsIds.push(parsedMesh.materialId);
  53280. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53281. if (!mat) {
  53282. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53283. }
  53284. else {
  53285. log += "\n\tMaterial " + mat.toString(fullDetails);
  53286. }
  53287. }
  53288. }
  53289. // Skeleton ?
  53290. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53291. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53292. if (skeletonAlreadyLoaded === false) {
  53293. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53294. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53295. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53296. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53297. skeletons.push(skeleton);
  53298. loadedSkeletonsIds.push(parsedSkeleton.id);
  53299. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53300. }
  53301. }
  53302. }
  53303. }
  53304. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53305. meshes.push(mesh);
  53306. log += "\n\tMesh " + mesh.toString(fullDetails);
  53307. }
  53308. }
  53309. // Connecting parents
  53310. var currentMesh;
  53311. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53312. currentMesh = scene.meshes[index];
  53313. if (currentMesh._waitingParentId) {
  53314. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53315. currentMesh._waitingParentId = null;
  53316. }
  53317. }
  53318. // freeze and compute world matrix application
  53319. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53320. currentMesh = scene.meshes[index];
  53321. if (currentMesh._waitingFreezeWorldMatrix) {
  53322. currentMesh.freezeWorldMatrix();
  53323. currentMesh._waitingFreezeWorldMatrix = null;
  53324. }
  53325. else {
  53326. currentMesh.computeWorldMatrix(true);
  53327. }
  53328. }
  53329. }
  53330. // Particles
  53331. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53332. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53333. var parsedParticleSystem = parsedData.particleSystems[index];
  53334. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53335. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53336. }
  53337. }
  53338. }
  53339. return true;
  53340. }
  53341. catch (err) {
  53342. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53343. if (onError) {
  53344. onError(msg, err);
  53345. }
  53346. else {
  53347. BABYLON.Tools.Log(msg);
  53348. throw err;
  53349. }
  53350. }
  53351. finally {
  53352. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53353. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53354. }
  53355. }
  53356. return false;
  53357. },
  53358. load: function (scene, data, rootUrl, onError) {
  53359. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53360. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53361. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53362. // and avoid problems with multiple concurrent .babylon loads.
  53363. var log = "importScene has failed JSON parse";
  53364. try {
  53365. var parsedData = JSON.parse(data);
  53366. log = "";
  53367. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53368. // Scene
  53369. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53370. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53371. }
  53372. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53373. scene.autoClear = parsedData.autoClear;
  53374. }
  53375. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53376. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53377. }
  53378. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53379. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53380. }
  53381. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53382. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53383. }
  53384. // Fog
  53385. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53386. scene.fogMode = parsedData.fogMode;
  53387. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53388. scene.fogStart = parsedData.fogStart;
  53389. scene.fogEnd = parsedData.fogEnd;
  53390. scene.fogDensity = parsedData.fogDensity;
  53391. log += "\tFog mode for scene: ";
  53392. switch (scene.fogMode) {
  53393. // getters not compiling, so using hardcoded
  53394. case 1:
  53395. log += "exp\n";
  53396. break;
  53397. case 2:
  53398. log += "exp2\n";
  53399. break;
  53400. case 3:
  53401. log += "linear\n";
  53402. break;
  53403. }
  53404. }
  53405. //Physics
  53406. if (parsedData.physicsEnabled) {
  53407. var physicsPlugin;
  53408. if (parsedData.physicsEngine === "cannon") {
  53409. physicsPlugin = new BABYLON.CannonJSPlugin();
  53410. }
  53411. else if (parsedData.physicsEngine === "oimo") {
  53412. physicsPlugin = new BABYLON.OimoJSPlugin();
  53413. }
  53414. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53415. //else - default engine, which is currently oimo
  53416. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53417. scene.enablePhysics(physicsGravity, physicsPlugin);
  53418. }
  53419. // Metadata
  53420. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53421. scene.metadata = parsedData.metadata;
  53422. }
  53423. //collisions, if defined. otherwise, default is true
  53424. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53425. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53426. }
  53427. scene.workerCollisions = !!parsedData.workerCollisions;
  53428. var index;
  53429. var cache;
  53430. // Lights
  53431. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53432. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53433. var parsedLight = parsedData.lights[index];
  53434. var light = BABYLON.Light.Parse(parsedLight, scene);
  53435. if (light) {
  53436. log += (index === 0 ? "\n\tLights:" : "");
  53437. log += "\n\t\t" + light.toString(fullDetails);
  53438. }
  53439. }
  53440. }
  53441. // Animations
  53442. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53443. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53444. var parsedAnimation = parsedData.animations[index];
  53445. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53446. scene.animations.push(animation);
  53447. log += (index === 0 ? "\n\tAnimations:" : "");
  53448. log += "\n\t\t" + animation.toString(fullDetails);
  53449. }
  53450. }
  53451. if (parsedData.autoAnimate) {
  53452. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53453. }
  53454. // Materials
  53455. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53456. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53457. var parsedMaterial = parsedData.materials[index];
  53458. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53459. log += (index === 0 ? "\n\tMaterials:" : "");
  53460. log += "\n\t\t" + mat.toString(fullDetails);
  53461. }
  53462. }
  53463. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53464. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53465. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53466. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53467. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53468. log += "\n\t\t" + mmat.toString(fullDetails);
  53469. }
  53470. }
  53471. // Morph targets
  53472. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53473. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53474. var managerData = _a[_i];
  53475. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53476. }
  53477. }
  53478. // Skeletons
  53479. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53480. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53481. var parsedSkeleton = parsedData.skeletons[index];
  53482. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53483. log += (index === 0 ? "\n\tSkeletons:" : "");
  53484. log += "\n\t\t" + skeleton.toString(fullDetails);
  53485. }
  53486. }
  53487. // Geometries
  53488. var geometries = parsedData.geometries;
  53489. if (geometries !== undefined && geometries !== null) {
  53490. // Boxes
  53491. var boxes = geometries.boxes;
  53492. if (boxes !== undefined && boxes !== null) {
  53493. for (index = 0, cache = boxes.length; index < cache; index++) {
  53494. var parsedBox = boxes[index];
  53495. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53496. }
  53497. }
  53498. // Spheres
  53499. var spheres = geometries.spheres;
  53500. if (spheres !== undefined && spheres !== null) {
  53501. for (index = 0, cache = spheres.length; index < cache; index++) {
  53502. var parsedSphere = spheres[index];
  53503. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53504. }
  53505. }
  53506. // Cylinders
  53507. var cylinders = geometries.cylinders;
  53508. if (cylinders !== undefined && cylinders !== null) {
  53509. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53510. var parsedCylinder = cylinders[index];
  53511. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53512. }
  53513. }
  53514. // Toruses
  53515. var toruses = geometries.toruses;
  53516. if (toruses !== undefined && toruses !== null) {
  53517. for (index = 0, cache = toruses.length; index < cache; index++) {
  53518. var parsedTorus = toruses[index];
  53519. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53520. }
  53521. }
  53522. // Grounds
  53523. var grounds = geometries.grounds;
  53524. if (grounds !== undefined && grounds !== null) {
  53525. for (index = 0, cache = grounds.length; index < cache; index++) {
  53526. var parsedGround = grounds[index];
  53527. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53528. }
  53529. }
  53530. // Planes
  53531. var planes = geometries.planes;
  53532. if (planes !== undefined && planes !== null) {
  53533. for (index = 0, cache = planes.length; index < cache; index++) {
  53534. var parsedPlane = planes[index];
  53535. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53536. }
  53537. }
  53538. // TorusKnots
  53539. var torusKnots = geometries.torusKnots;
  53540. if (torusKnots !== undefined && torusKnots !== null) {
  53541. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53542. var parsedTorusKnot = torusKnots[index];
  53543. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53544. }
  53545. }
  53546. // VertexData
  53547. var vertexData = geometries.vertexData;
  53548. if (vertexData !== undefined && vertexData !== null) {
  53549. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53550. var parsedVertexData = vertexData[index];
  53551. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53552. }
  53553. }
  53554. }
  53555. // Transform nodes
  53556. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53557. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53558. var parsedTransformNode = parsedData.transformNodes[index];
  53559. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53560. }
  53561. }
  53562. // Meshes
  53563. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53564. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53565. var parsedMesh = parsedData.meshes[index];
  53566. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53567. log += (index === 0 ? "\n\tMeshes:" : "");
  53568. log += "\n\t\t" + mesh.toString(fullDetails);
  53569. }
  53570. }
  53571. // Cameras
  53572. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53573. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53574. var parsedCamera = parsedData.cameras[index];
  53575. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53576. log += (index === 0 ? "\n\tCameras:" : "");
  53577. log += "\n\t\t" + camera.toString(fullDetails);
  53578. }
  53579. }
  53580. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53581. scene.setActiveCameraByID(parsedData.activeCameraID);
  53582. }
  53583. // Browsing all the graph to connect the dots
  53584. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53585. var camera = scene.cameras[index];
  53586. if (camera._waitingParentId) {
  53587. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53588. camera._waitingParentId = null;
  53589. }
  53590. }
  53591. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53592. var light_1 = scene.lights[index];
  53593. if (light_1 && light_1._waitingParentId) {
  53594. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53595. light_1._waitingParentId = null;
  53596. }
  53597. }
  53598. // Sounds
  53599. var loadedSounds = [];
  53600. var loadedSound;
  53601. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53602. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53603. var parsedSound = parsedData.sounds[index];
  53604. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53605. if (!parsedSound.url)
  53606. parsedSound.url = parsedSound.name;
  53607. if (!loadedSounds[parsedSound.url]) {
  53608. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53609. loadedSounds[parsedSound.url] = loadedSound;
  53610. }
  53611. else {
  53612. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53613. }
  53614. }
  53615. else {
  53616. new BABYLON.Sound(parsedSound.name, null, scene);
  53617. }
  53618. }
  53619. }
  53620. loadedSounds = [];
  53621. // Connect parents & children and parse actions
  53622. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53623. var transformNode = scene.transformNodes[index];
  53624. if (transformNode._waitingParentId) {
  53625. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53626. transformNode._waitingParentId = null;
  53627. }
  53628. }
  53629. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53630. var mesh = scene.meshes[index];
  53631. if (mesh._waitingParentId) {
  53632. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53633. mesh._waitingParentId = null;
  53634. }
  53635. if (mesh._waitingActions) {
  53636. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53637. mesh._waitingActions = null;
  53638. }
  53639. }
  53640. // freeze world matrix application
  53641. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53642. var currentMesh = scene.meshes[index];
  53643. if (currentMesh._waitingFreezeWorldMatrix) {
  53644. currentMesh.freezeWorldMatrix();
  53645. currentMesh._waitingFreezeWorldMatrix = null;
  53646. }
  53647. else {
  53648. currentMesh.computeWorldMatrix(true);
  53649. }
  53650. }
  53651. // Particles Systems
  53652. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53653. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53654. var parsedParticleSystem = parsedData.particleSystems[index];
  53655. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53656. }
  53657. }
  53658. // Environment texture
  53659. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53660. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53661. if (parsedData.createDefaultSkybox === true) {
  53662. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53663. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53664. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53665. }
  53666. }
  53667. // Lens flares
  53668. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53669. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53670. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53671. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53672. }
  53673. }
  53674. // Shadows
  53675. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53676. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53677. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53678. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53679. }
  53680. }
  53681. // Lights exclusions / inclusions
  53682. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53683. var light_2 = scene.lights[index];
  53684. // Excluded check
  53685. if (light_2._excludedMeshesIds.length > 0) {
  53686. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53687. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53688. if (excludedMesh) {
  53689. light_2.excludedMeshes.push(excludedMesh);
  53690. }
  53691. }
  53692. light_2._excludedMeshesIds = [];
  53693. }
  53694. // Included check
  53695. if (light_2._includedOnlyMeshesIds.length > 0) {
  53696. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53697. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53698. if (includedOnlyMesh) {
  53699. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53700. }
  53701. }
  53702. light_2._includedOnlyMeshesIds = [];
  53703. }
  53704. }
  53705. // Actions (scene)
  53706. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53707. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53708. }
  53709. // Finish
  53710. return true;
  53711. }
  53712. catch (err) {
  53713. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53714. if (onError) {
  53715. onError(msg, err);
  53716. }
  53717. else {
  53718. BABYLON.Tools.Log(msg);
  53719. throw err;
  53720. }
  53721. }
  53722. finally {
  53723. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53724. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53725. }
  53726. }
  53727. return false;
  53728. }
  53729. });
  53730. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53731. })(BABYLON || (BABYLON = {}));
  53732. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53733. var BABYLON;
  53734. (function (BABYLON) {
  53735. var FilesInput = /** @class */ (function () {
  53736. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53737. this.onProcessFileCallback = function () { return true; };
  53738. this._engine = engine;
  53739. this._currentScene = scene;
  53740. this._sceneLoadedCallback = sceneLoadedCallback;
  53741. this._progressCallback = progressCallback;
  53742. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53743. this._textureLoadingCallback = textureLoadingCallback;
  53744. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53745. this._onReloadCallback = onReloadCallback;
  53746. this._errorCallback = errorCallback;
  53747. }
  53748. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53749. var _this = this;
  53750. if (elementToMonitor) {
  53751. this._elementToMonitor = elementToMonitor;
  53752. this._dragEnterHandler = function (e) { _this.drag(e); };
  53753. this._dragOverHandler = function (e) { _this.drag(e); };
  53754. this._dropHandler = function (e) { _this.drop(e); };
  53755. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53756. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53757. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53758. }
  53759. };
  53760. FilesInput.prototype.dispose = function () {
  53761. if (!this._elementToMonitor) {
  53762. return;
  53763. }
  53764. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53765. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53766. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53767. };
  53768. FilesInput.prototype.renderFunction = function () {
  53769. if (this._additionalRenderLoopLogicCallback) {
  53770. this._additionalRenderLoopLogicCallback();
  53771. }
  53772. if (this._currentScene) {
  53773. if (this._textureLoadingCallback) {
  53774. var remaining = this._currentScene.getWaitingItemsCount();
  53775. if (remaining > 0) {
  53776. this._textureLoadingCallback(remaining);
  53777. }
  53778. }
  53779. this._currentScene.render();
  53780. }
  53781. };
  53782. FilesInput.prototype.drag = function (e) {
  53783. e.stopPropagation();
  53784. e.preventDefault();
  53785. };
  53786. FilesInput.prototype.drop = function (eventDrop) {
  53787. eventDrop.stopPropagation();
  53788. eventDrop.preventDefault();
  53789. this.loadFiles(eventDrop);
  53790. };
  53791. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53792. var _this = this;
  53793. var reader = folder.createReader();
  53794. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53795. reader.readEntries(function (entries) {
  53796. remaining.count += entries.length;
  53797. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53798. var entry = entries_1[_i];
  53799. if (entry.isFile) {
  53800. entry.file(function (file) {
  53801. file.correctName = relativePath + file.name;
  53802. files.push(file);
  53803. if (--remaining.count === 0) {
  53804. callback();
  53805. }
  53806. });
  53807. }
  53808. else if (entry.isDirectory) {
  53809. _this._traverseFolder(entry, files, remaining, callback);
  53810. }
  53811. }
  53812. if (--remaining.count) {
  53813. callback();
  53814. }
  53815. });
  53816. };
  53817. FilesInput.prototype._processFiles = function (files) {
  53818. var skippedFiles = 0;
  53819. for (var i = 0; i < files.length; i++) {
  53820. var name = files[i].correctName.toLowerCase();
  53821. var extension = name.split('.').pop();
  53822. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53823. skippedFiles++;
  53824. continue;
  53825. }
  53826. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53827. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53828. this._sceneFileToLoad = files[i];
  53829. }
  53830. else {
  53831. FilesInput.FilesToLoad[name] = files[i];
  53832. }
  53833. }
  53834. if (this._onReloadCallback) {
  53835. this._onReloadCallback(this._sceneFileToLoad);
  53836. }
  53837. else if (skippedFiles < files.length) {
  53838. this.reload();
  53839. }
  53840. };
  53841. FilesInput.prototype.loadFiles = function (event) {
  53842. var _this = this;
  53843. if (this._startingProcessingFilesCallback)
  53844. this._startingProcessingFilesCallback();
  53845. // Handling data transfer via drag'n'drop
  53846. if (event && event.dataTransfer && event.dataTransfer.files) {
  53847. this._filesToLoad = event.dataTransfer.files;
  53848. }
  53849. // Handling files from input files
  53850. if (event && event.target && event.target.files) {
  53851. this._filesToLoad = event.target.files;
  53852. }
  53853. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53854. var files_1 = new Array();
  53855. var folders = [];
  53856. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53857. for (var i = 0; i < this._filesToLoad.length; i++) {
  53858. var fileToLoad = this._filesToLoad[i];
  53859. var name_1 = fileToLoad.name.toLowerCase();
  53860. var entry = void 0;
  53861. fileToLoad.correctName = name_1;
  53862. if (items) {
  53863. var item = items[i];
  53864. if (item.getAsEntry) {
  53865. entry = item.getAsEntry();
  53866. }
  53867. else if (item.webkitGetAsEntry) {
  53868. entry = item.webkitGetAsEntry();
  53869. }
  53870. }
  53871. if (!entry) {
  53872. files_1.push(fileToLoad);
  53873. }
  53874. else {
  53875. if (entry.isDirectory) {
  53876. folders.push(entry);
  53877. }
  53878. else {
  53879. files_1.push(fileToLoad);
  53880. }
  53881. }
  53882. }
  53883. if (folders.length === 0) {
  53884. this._processFiles(files_1);
  53885. }
  53886. else {
  53887. var remaining = { count: folders.length };
  53888. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53889. var folder = folders_1[_i];
  53890. this._traverseFolder(folder, files_1, remaining, function () {
  53891. _this._processFiles(files_1);
  53892. });
  53893. }
  53894. }
  53895. }
  53896. };
  53897. FilesInput.prototype.reload = function () {
  53898. var _this = this;
  53899. // If a ".babylon" file has been provided
  53900. if (this._sceneFileToLoad) {
  53901. if (this._currentScene) {
  53902. if (BABYLON.Tools.errorsCount > 0) {
  53903. BABYLON.Tools.ClearLogCache();
  53904. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53905. }
  53906. this._engine.stopRenderLoop();
  53907. this._currentScene.dispose();
  53908. }
  53909. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53910. _this._currentScene = newScene;
  53911. if (_this._sceneLoadedCallback) {
  53912. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53913. }
  53914. // Wait for textures and shaders to be ready
  53915. _this._currentScene.executeWhenReady(function () {
  53916. _this._engine.runRenderLoop(function () {
  53917. _this.renderFunction();
  53918. });
  53919. });
  53920. }, function (progress) {
  53921. if (_this._progressCallback) {
  53922. _this._progressCallback(progress);
  53923. }
  53924. }, function (scene, message) {
  53925. _this._currentScene = scene;
  53926. if (_this._errorCallback) {
  53927. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53928. }
  53929. });
  53930. }
  53931. else {
  53932. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53933. }
  53934. };
  53935. FilesInput.FilesToLoad = {};
  53936. return FilesInput;
  53937. }());
  53938. BABYLON.FilesInput = FilesInput;
  53939. })(BABYLON || (BABYLON = {}));
  53940. //# sourceMappingURL=babylon.filesInput.js.map
  53941. var BABYLON;
  53942. (function (BABYLON) {
  53943. /**
  53944. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53945. * The underlying implementation relies on an associative array to ensure the best performances.
  53946. * The value can be anything including 'null' but except 'undefined'
  53947. */
  53948. var StringDictionary = /** @class */ (function () {
  53949. function StringDictionary() {
  53950. this._count = 0;
  53951. this._data = {};
  53952. }
  53953. /**
  53954. * This will clear this dictionary and copy the content from the 'source' one.
  53955. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53956. * @param source the dictionary to take the content from and copy to this dictionary
  53957. */
  53958. StringDictionary.prototype.copyFrom = function (source) {
  53959. var _this = this;
  53960. this.clear();
  53961. source.forEach(function (t, v) { return _this.add(t, v); });
  53962. };
  53963. /**
  53964. * Get a value based from its key
  53965. * @param key the given key to get the matching value from
  53966. * @return the value if found, otherwise undefined is returned
  53967. */
  53968. StringDictionary.prototype.get = function (key) {
  53969. var val = this._data[key];
  53970. if (val !== undefined) {
  53971. return val;
  53972. }
  53973. return undefined;
  53974. };
  53975. /**
  53976. * Get a value from its key or add it if it doesn't exist.
  53977. * This method will ensure you that a given key/data will be present in the dictionary.
  53978. * @param key the given key to get the matching value from
  53979. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53980. * The factory will only be invoked if there's no data for the given key.
  53981. * @return the value corresponding to the key.
  53982. */
  53983. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53984. var val = this.get(key);
  53985. if (val !== undefined) {
  53986. return val;
  53987. }
  53988. val = factory(key);
  53989. if (val) {
  53990. this.add(key, val);
  53991. }
  53992. return val;
  53993. };
  53994. /**
  53995. * Get a value from its key if present in the dictionary otherwise add it
  53996. * @param key the key to get the value from
  53997. * @param val if there's no such key/value pair in the dictionary add it with this value
  53998. * @return the value corresponding to the key
  53999. */
  54000. StringDictionary.prototype.getOrAdd = function (key, val) {
  54001. var curVal = this.get(key);
  54002. if (curVal !== undefined) {
  54003. return curVal;
  54004. }
  54005. this.add(key, val);
  54006. return val;
  54007. };
  54008. /**
  54009. * Check if there's a given key in the dictionary
  54010. * @param key the key to check for
  54011. * @return true if the key is present, false otherwise
  54012. */
  54013. StringDictionary.prototype.contains = function (key) {
  54014. return this._data[key] !== undefined;
  54015. };
  54016. /**
  54017. * Add a new key and its corresponding value
  54018. * @param key the key to add
  54019. * @param value the value corresponding to the key
  54020. * @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
  54021. */
  54022. StringDictionary.prototype.add = function (key, value) {
  54023. if (this._data[key] !== undefined) {
  54024. return false;
  54025. }
  54026. this._data[key] = value;
  54027. ++this._count;
  54028. return true;
  54029. };
  54030. StringDictionary.prototype.set = function (key, value) {
  54031. if (this._data[key] === undefined) {
  54032. return false;
  54033. }
  54034. this._data[key] = value;
  54035. return true;
  54036. };
  54037. /**
  54038. * Get the element of the given key and remove it from the dictionary
  54039. * @param key
  54040. */
  54041. StringDictionary.prototype.getAndRemove = function (key) {
  54042. var val = this.get(key);
  54043. if (val !== undefined) {
  54044. delete this._data[key];
  54045. --this._count;
  54046. return val;
  54047. }
  54048. return null;
  54049. };
  54050. /**
  54051. * Remove a key/value from the dictionary.
  54052. * @param key the key to remove
  54053. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54054. */
  54055. StringDictionary.prototype.remove = function (key) {
  54056. if (this.contains(key)) {
  54057. delete this._data[key];
  54058. --this._count;
  54059. return true;
  54060. }
  54061. return false;
  54062. };
  54063. /**
  54064. * Clear the whole content of the dictionary
  54065. */
  54066. StringDictionary.prototype.clear = function () {
  54067. this._data = {};
  54068. this._count = 0;
  54069. };
  54070. Object.defineProperty(StringDictionary.prototype, "count", {
  54071. get: function () {
  54072. return this._count;
  54073. },
  54074. enumerable: true,
  54075. configurable: true
  54076. });
  54077. /**
  54078. * Execute a callback on each key/val of the dictionary.
  54079. * Note that you can remove any element in this dictionary in the callback implementation
  54080. * @param callback the callback to execute on a given key/value pair
  54081. */
  54082. StringDictionary.prototype.forEach = function (callback) {
  54083. for (var cur in this._data) {
  54084. var val = this._data[cur];
  54085. callback(cur, val);
  54086. }
  54087. };
  54088. /**
  54089. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54090. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54091. * Note that you can remove any element in this dictionary in the callback implementation
  54092. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54093. */
  54094. StringDictionary.prototype.first = function (callback) {
  54095. for (var cur in this._data) {
  54096. var val = this._data[cur];
  54097. var res = callback(cur, val);
  54098. if (res) {
  54099. return res;
  54100. }
  54101. }
  54102. return null;
  54103. };
  54104. return StringDictionary;
  54105. }());
  54106. BABYLON.StringDictionary = StringDictionary;
  54107. })(BABYLON || (BABYLON = {}));
  54108. //# sourceMappingURL=babylon.stringDictionary.js.map
  54109. var BABYLON;
  54110. (function (BABYLON) {
  54111. var Tags = /** @class */ (function () {
  54112. function Tags() {
  54113. }
  54114. Tags.EnableFor = function (obj) {
  54115. obj._tags = obj._tags || {};
  54116. obj.hasTags = function () {
  54117. return Tags.HasTags(obj);
  54118. };
  54119. obj.addTags = function (tagsString) {
  54120. return Tags.AddTagsTo(obj, tagsString);
  54121. };
  54122. obj.removeTags = function (tagsString) {
  54123. return Tags.RemoveTagsFrom(obj, tagsString);
  54124. };
  54125. obj.matchesTagsQuery = function (tagsQuery) {
  54126. return Tags.MatchesQuery(obj, tagsQuery);
  54127. };
  54128. };
  54129. Tags.DisableFor = function (obj) {
  54130. delete obj._tags;
  54131. delete obj.hasTags;
  54132. delete obj.addTags;
  54133. delete obj.removeTags;
  54134. delete obj.matchesTagsQuery;
  54135. };
  54136. Tags.HasTags = function (obj) {
  54137. if (!obj._tags) {
  54138. return false;
  54139. }
  54140. return !BABYLON.Tools.IsEmpty(obj._tags);
  54141. };
  54142. Tags.GetTags = function (obj, asString) {
  54143. if (asString === void 0) { asString = true; }
  54144. if (!obj._tags) {
  54145. return null;
  54146. }
  54147. if (asString) {
  54148. var tagsArray = [];
  54149. for (var tag in obj._tags) {
  54150. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54151. tagsArray.push(tag);
  54152. }
  54153. }
  54154. return tagsArray.join(" ");
  54155. }
  54156. else {
  54157. return obj._tags;
  54158. }
  54159. };
  54160. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54161. // a tag cannot start with '||', '&&', and '!'
  54162. // it cannot contain whitespaces
  54163. Tags.AddTagsTo = function (obj, tagsString) {
  54164. if (!tagsString) {
  54165. return;
  54166. }
  54167. if (typeof tagsString !== "string") {
  54168. return;
  54169. }
  54170. var tags = tagsString.split(" ");
  54171. tags.forEach(function (tag, index, array) {
  54172. Tags._AddTagTo(obj, tag);
  54173. });
  54174. };
  54175. Tags._AddTagTo = function (obj, tag) {
  54176. tag = tag.trim();
  54177. if (tag === "" || tag === "true" || tag === "false") {
  54178. return;
  54179. }
  54180. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54181. return;
  54182. }
  54183. Tags.EnableFor(obj);
  54184. obj._tags[tag] = true;
  54185. };
  54186. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54187. if (!Tags.HasTags(obj)) {
  54188. return;
  54189. }
  54190. var tags = tagsString.split(" ");
  54191. for (var t in tags) {
  54192. Tags._RemoveTagFrom(obj, tags[t]);
  54193. }
  54194. };
  54195. Tags._RemoveTagFrom = function (obj, tag) {
  54196. delete obj._tags[tag];
  54197. };
  54198. Tags.MatchesQuery = function (obj, tagsQuery) {
  54199. if (tagsQuery === undefined) {
  54200. return true;
  54201. }
  54202. if (tagsQuery === "") {
  54203. return Tags.HasTags(obj);
  54204. }
  54205. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54206. };
  54207. return Tags;
  54208. }());
  54209. BABYLON.Tags = Tags;
  54210. })(BABYLON || (BABYLON = {}));
  54211. //# sourceMappingURL=babylon.tags.js.map
  54212. var BABYLON;
  54213. (function (BABYLON) {
  54214. var Internals;
  54215. (function (Internals) {
  54216. var AndOrNotEvaluator = /** @class */ (function () {
  54217. function AndOrNotEvaluator() {
  54218. }
  54219. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54220. if (!query.match(/\([^\(\)]*\)/g)) {
  54221. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54222. }
  54223. else {
  54224. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54225. // remove parenthesis
  54226. r = r.slice(1, r.length - 1);
  54227. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54228. });
  54229. }
  54230. if (query === "true") {
  54231. return true;
  54232. }
  54233. if (query === "false") {
  54234. return false;
  54235. }
  54236. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54237. };
  54238. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54239. evaluateCallback = evaluateCallback || (function (r) {
  54240. return r === "true" ? true : false;
  54241. });
  54242. var result;
  54243. var or = parenthesisContent.split("||");
  54244. for (var i in or) {
  54245. if (or.hasOwnProperty(i)) {
  54246. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54247. var and = ori.split("&&");
  54248. if (and.length > 1) {
  54249. for (var j = 0; j < and.length; ++j) {
  54250. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54251. if (andj !== "true" && andj !== "false") {
  54252. if (andj[0] === "!") {
  54253. result = !evaluateCallback(andj.substring(1));
  54254. }
  54255. else {
  54256. result = evaluateCallback(andj);
  54257. }
  54258. }
  54259. else {
  54260. result = andj === "true" ? true : false;
  54261. }
  54262. if (!result) {
  54263. ori = "false";
  54264. break;
  54265. }
  54266. }
  54267. }
  54268. if (result || ori === "true") {
  54269. result = true;
  54270. break;
  54271. }
  54272. // result equals false (or undefined)
  54273. if (ori !== "true" && ori !== "false") {
  54274. if (ori[0] === "!") {
  54275. result = !evaluateCallback(ori.substring(1));
  54276. }
  54277. else {
  54278. result = evaluateCallback(ori);
  54279. }
  54280. }
  54281. else {
  54282. result = ori === "true" ? true : false;
  54283. }
  54284. }
  54285. }
  54286. // the whole parenthesis scope is replaced by 'true' or 'false'
  54287. return result ? "true" : "false";
  54288. };
  54289. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54290. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54291. // remove whitespaces
  54292. r = r.replace(/[\s]/g, function () { return ""; });
  54293. return r.length % 2 ? "!" : "";
  54294. });
  54295. booleanString = booleanString.trim();
  54296. if (booleanString === "!true") {
  54297. booleanString = "false";
  54298. }
  54299. else if (booleanString === "!false") {
  54300. booleanString = "true";
  54301. }
  54302. return booleanString;
  54303. };
  54304. return AndOrNotEvaluator;
  54305. }());
  54306. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54308. })(BABYLON || (BABYLON = {}));
  54309. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54310. var BABYLON;
  54311. (function (BABYLON) {
  54312. var Database = /** @class */ (function () {
  54313. function Database(urlToScene, callbackManifestChecked) {
  54314. // Handling various flavors of prefixed version of IndexedDB
  54315. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54316. this.callbackManifestChecked = callbackManifestChecked;
  54317. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54318. this.db = null;
  54319. this._enableSceneOffline = false;
  54320. this._enableTexturesOffline = false;
  54321. this.manifestVersionFound = 0;
  54322. this.mustUpdateRessources = false;
  54323. this.hasReachedQuota = false;
  54324. if (!Database.IDBStorageEnabled) {
  54325. this.callbackManifestChecked(true);
  54326. }
  54327. else {
  54328. this.checkManifestFile();
  54329. }
  54330. }
  54331. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54332. get: function () {
  54333. return this._enableSceneOffline;
  54334. },
  54335. enumerable: true,
  54336. configurable: true
  54337. });
  54338. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54339. get: function () {
  54340. return this._enableTexturesOffline;
  54341. },
  54342. enumerable: true,
  54343. configurable: true
  54344. });
  54345. Database.prototype.checkManifestFile = function () {
  54346. var _this = this;
  54347. var noManifestFile = function () {
  54348. _this._enableSceneOffline = false;
  54349. _this._enableTexturesOffline = false;
  54350. _this.callbackManifestChecked(false);
  54351. };
  54352. var timeStampUsed = false;
  54353. var manifestURL = this.currentSceneUrl + ".manifest";
  54354. var xhr = new XMLHttpRequest();
  54355. if (navigator.onLine) {
  54356. // Adding a timestamp to by-pass browsers' cache
  54357. timeStampUsed = true;
  54358. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54359. }
  54360. xhr.open("GET", manifestURL, true);
  54361. xhr.addEventListener("load", function () {
  54362. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54363. try {
  54364. var manifestFile = JSON.parse(xhr.response);
  54365. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54366. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54367. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54368. _this.manifestVersionFound = manifestFile.version;
  54369. }
  54370. if (_this.callbackManifestChecked) {
  54371. _this.callbackManifestChecked(true);
  54372. }
  54373. }
  54374. catch (ex) {
  54375. noManifestFile();
  54376. }
  54377. }
  54378. else {
  54379. noManifestFile();
  54380. }
  54381. }, false);
  54382. xhr.addEventListener("error", function (event) {
  54383. if (timeStampUsed) {
  54384. timeStampUsed = false;
  54385. // Let's retry without the timeStamp
  54386. // It could fail when coupled with HTML5 Offline API
  54387. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54388. xhr.open("GET", retryManifestURL, true);
  54389. xhr.send();
  54390. }
  54391. else {
  54392. noManifestFile();
  54393. }
  54394. }, false);
  54395. try {
  54396. xhr.send();
  54397. }
  54398. catch (ex) {
  54399. BABYLON.Tools.Error("Error on XHR send request.");
  54400. this.callbackManifestChecked(false);
  54401. }
  54402. };
  54403. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54404. var _this = this;
  54405. var handleError = function () {
  54406. _this.isSupported = false;
  54407. if (errorCallback)
  54408. errorCallback();
  54409. };
  54410. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54411. // Your browser doesn't support IndexedDB
  54412. this.isSupported = false;
  54413. if (errorCallback)
  54414. errorCallback();
  54415. }
  54416. else {
  54417. // If the DB hasn't been opened or created yet
  54418. if (!this.db) {
  54419. this.hasReachedQuota = false;
  54420. this.isSupported = true;
  54421. var request = this.idbFactory.open("babylonjs", 1);
  54422. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54423. request.onerror = function (event) {
  54424. handleError();
  54425. };
  54426. // executes when a version change transaction cannot complete due to other active transactions
  54427. request.onblocked = function (event) {
  54428. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54429. handleError();
  54430. };
  54431. // DB has been opened successfully
  54432. request.onsuccess = function (event) {
  54433. _this.db = request.result;
  54434. successCallback();
  54435. };
  54436. // Initialization of the DB. Creating Scenes & Textures stores
  54437. request.onupgradeneeded = function (event) {
  54438. _this.db = (event.target).result;
  54439. if (_this.db) {
  54440. try {
  54441. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54442. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54443. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54444. }
  54445. catch (ex) {
  54446. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54447. handleError();
  54448. }
  54449. }
  54450. };
  54451. }
  54452. else {
  54453. if (successCallback)
  54454. successCallback();
  54455. }
  54456. }
  54457. };
  54458. Database.prototype.loadImageFromDB = function (url, image) {
  54459. var _this = this;
  54460. var completeURL = Database.ReturnFullUrlLocation(url);
  54461. var saveAndLoadImage = function () {
  54462. if (!_this.hasReachedQuota && _this.db !== null) {
  54463. // the texture is not yet in the DB, let's try to save it
  54464. _this._saveImageIntoDBAsync(completeURL, image);
  54465. }
  54466. else {
  54467. image.src = url;
  54468. }
  54469. };
  54470. if (!this.mustUpdateRessources) {
  54471. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54472. }
  54473. else {
  54474. saveAndLoadImage();
  54475. }
  54476. };
  54477. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54478. if (this.isSupported && this.db !== null) {
  54479. var texture;
  54480. var transaction = this.db.transaction(["textures"]);
  54481. transaction.onabort = function (event) {
  54482. image.src = url;
  54483. };
  54484. transaction.oncomplete = function (event) {
  54485. var blobTextureURL;
  54486. if (texture) {
  54487. var URL = window.URL || window.webkitURL;
  54488. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54489. image.onerror = function () {
  54490. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54491. image.src = url;
  54492. };
  54493. image.src = blobTextureURL;
  54494. }
  54495. else {
  54496. notInDBCallback();
  54497. }
  54498. };
  54499. var getRequest = transaction.objectStore("textures").get(url);
  54500. getRequest.onsuccess = function (event) {
  54501. texture = (event.target).result;
  54502. };
  54503. getRequest.onerror = function (event) {
  54504. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54505. image.src = url;
  54506. };
  54507. }
  54508. else {
  54509. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54510. image.src = url;
  54511. }
  54512. };
  54513. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54514. var _this = this;
  54515. if (this.isSupported) {
  54516. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54517. var generateBlobUrl = function () {
  54518. var blobTextureURL;
  54519. if (blob) {
  54520. var URL = window.URL || window.webkitURL;
  54521. try {
  54522. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54523. }
  54524. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54525. catch (ex) {
  54526. blobTextureURL = URL.createObjectURL(blob);
  54527. }
  54528. }
  54529. if (blobTextureURL) {
  54530. image.src = blobTextureURL;
  54531. }
  54532. };
  54533. if (Database.IsUASupportingBlobStorage) {
  54534. var xhr = new XMLHttpRequest(), blob;
  54535. xhr.open("GET", url, true);
  54536. xhr.responseType = "blob";
  54537. xhr.addEventListener("load", function () {
  54538. if (xhr.status === 200 && _this.db) {
  54539. // Blob as response (XHR2)
  54540. blob = xhr.response;
  54541. var transaction = _this.db.transaction(["textures"], "readwrite");
  54542. // the transaction could abort because of a QuotaExceededError error
  54543. transaction.onabort = function (event) {
  54544. try {
  54545. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54546. var srcElement = (event.srcElement || event.target);
  54547. var error = srcElement.error;
  54548. if (error && error.name === "QuotaExceededError") {
  54549. _this.hasReachedQuota = true;
  54550. }
  54551. }
  54552. catch (ex) { }
  54553. generateBlobUrl();
  54554. };
  54555. transaction.oncomplete = function (event) {
  54556. generateBlobUrl();
  54557. };
  54558. var newTexture = { textureUrl: url, data: blob };
  54559. try {
  54560. // Put the blob into the dabase
  54561. var addRequest = transaction.objectStore("textures").put(newTexture);
  54562. addRequest.onsuccess = function (event) {
  54563. };
  54564. addRequest.onerror = function (event) {
  54565. generateBlobUrl();
  54566. };
  54567. }
  54568. catch (ex) {
  54569. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54570. if (ex.code === 25) {
  54571. Database.IsUASupportingBlobStorage = false;
  54572. }
  54573. image.src = url;
  54574. }
  54575. }
  54576. else {
  54577. image.src = url;
  54578. }
  54579. }, false);
  54580. xhr.addEventListener("error", function (event) {
  54581. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54582. image.src = url;
  54583. }, false);
  54584. xhr.send();
  54585. }
  54586. else {
  54587. image.src = url;
  54588. }
  54589. }
  54590. else {
  54591. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54592. image.src = url;
  54593. }
  54594. };
  54595. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54596. var _this = this;
  54597. var updateVersion = function () {
  54598. // the version is not yet in the DB or we need to update it
  54599. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54600. };
  54601. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54602. };
  54603. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54604. var _this = this;
  54605. if (this.isSupported && this.db) {
  54606. var version;
  54607. try {
  54608. var transaction = this.db.transaction(["versions"]);
  54609. transaction.oncomplete = function (event) {
  54610. if (version) {
  54611. // If the version in the JSON file is > than the version in DB
  54612. if (_this.manifestVersionFound > version.data) {
  54613. _this.mustUpdateRessources = true;
  54614. updateInDBCallback();
  54615. }
  54616. else {
  54617. callback(version.data);
  54618. }
  54619. }
  54620. else {
  54621. _this.mustUpdateRessources = true;
  54622. updateInDBCallback();
  54623. }
  54624. };
  54625. transaction.onabort = function (event) {
  54626. callback(-1);
  54627. };
  54628. var getRequest = transaction.objectStore("versions").get(url);
  54629. getRequest.onsuccess = function (event) {
  54630. version = (event.target).result;
  54631. };
  54632. getRequest.onerror = function (event) {
  54633. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54634. callback(-1);
  54635. };
  54636. }
  54637. catch (ex) {
  54638. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54639. callback(-1);
  54640. }
  54641. }
  54642. else {
  54643. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54644. callback(-1);
  54645. }
  54646. };
  54647. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54648. var _this = this;
  54649. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54650. try {
  54651. // Open a transaction to the database
  54652. var transaction = this.db.transaction(["versions"], "readwrite");
  54653. // the transaction could abort because of a QuotaExceededError error
  54654. transaction.onabort = function (event) {
  54655. try {
  54656. var error = event.srcElement['error'];
  54657. if (error && error.name === "QuotaExceededError") {
  54658. _this.hasReachedQuota = true;
  54659. }
  54660. }
  54661. catch (ex) { }
  54662. callback(-1);
  54663. };
  54664. transaction.oncomplete = function (event) {
  54665. callback(_this.manifestVersionFound);
  54666. };
  54667. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54668. // Put the scene into the database
  54669. var addRequest = transaction.objectStore("versions").put(newVersion);
  54670. addRequest.onsuccess = function (event) {
  54671. };
  54672. addRequest.onerror = function (event) {
  54673. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54674. };
  54675. }
  54676. catch (ex) {
  54677. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54678. callback(-1);
  54679. }
  54680. }
  54681. else {
  54682. callback(-1);
  54683. }
  54684. };
  54685. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54686. var _this = this;
  54687. var completeUrl = Database.ReturnFullUrlLocation(url);
  54688. var saveAndLoadFile = function () {
  54689. // the scene is not yet in the DB, let's try to save it
  54690. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54691. };
  54692. this._checkVersionFromDB(completeUrl, function (version) {
  54693. if (version !== -1) {
  54694. if (!_this.mustUpdateRessources) {
  54695. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54696. }
  54697. else {
  54698. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54699. }
  54700. }
  54701. else {
  54702. if (errorCallback) {
  54703. errorCallback();
  54704. }
  54705. }
  54706. });
  54707. };
  54708. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54709. if (this.isSupported && this.db) {
  54710. var targetStore;
  54711. if (url.indexOf(".babylon") !== -1) {
  54712. targetStore = "scenes";
  54713. }
  54714. else {
  54715. targetStore = "textures";
  54716. }
  54717. var file;
  54718. var transaction = this.db.transaction([targetStore]);
  54719. transaction.oncomplete = function (event) {
  54720. if (file) {
  54721. callback(file.data);
  54722. }
  54723. else {
  54724. notInDBCallback();
  54725. }
  54726. };
  54727. transaction.onabort = function (event) {
  54728. notInDBCallback();
  54729. };
  54730. var getRequest = transaction.objectStore(targetStore).get(url);
  54731. getRequest.onsuccess = function (event) {
  54732. file = (event.target).result;
  54733. };
  54734. getRequest.onerror = function (event) {
  54735. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54736. notInDBCallback();
  54737. };
  54738. }
  54739. else {
  54740. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54741. callback();
  54742. }
  54743. };
  54744. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54745. var _this = this;
  54746. if (this.isSupported) {
  54747. var targetStore;
  54748. if (url.indexOf(".babylon") !== -1) {
  54749. targetStore = "scenes";
  54750. }
  54751. else {
  54752. targetStore = "textures";
  54753. }
  54754. // Create XHR
  54755. var xhr = new XMLHttpRequest();
  54756. var fileData;
  54757. xhr.open("GET", url, true);
  54758. if (useArrayBuffer) {
  54759. xhr.responseType = "arraybuffer";
  54760. }
  54761. if (progressCallback) {
  54762. xhr.onprogress = progressCallback;
  54763. }
  54764. xhr.addEventListener("load", function () {
  54765. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54766. // Blob as response (XHR2)
  54767. //fileData = xhr.responseText;
  54768. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54769. if (!_this.hasReachedQuota && _this.db) {
  54770. // Open a transaction to the database
  54771. var transaction = _this.db.transaction([targetStore], "readwrite");
  54772. // the transaction could abort because of a QuotaExceededError error
  54773. transaction.onabort = function (event) {
  54774. try {
  54775. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54776. var error = event.srcElement['error'];
  54777. if (error && error.name === "QuotaExceededError") {
  54778. _this.hasReachedQuota = true;
  54779. }
  54780. }
  54781. catch (ex) { }
  54782. callback(fileData);
  54783. };
  54784. transaction.oncomplete = function (event) {
  54785. callback(fileData);
  54786. };
  54787. var newFile;
  54788. if (targetStore === "scenes") {
  54789. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54790. }
  54791. else {
  54792. newFile = { textureUrl: url, data: fileData };
  54793. }
  54794. try {
  54795. // Put the scene into the database
  54796. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54797. addRequest.onsuccess = function (event) {
  54798. };
  54799. addRequest.onerror = function (event) {
  54800. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54801. };
  54802. }
  54803. catch (ex) {
  54804. callback(fileData);
  54805. }
  54806. }
  54807. else {
  54808. callback(fileData);
  54809. }
  54810. }
  54811. else {
  54812. callback();
  54813. }
  54814. }, false);
  54815. xhr.addEventListener("error", function (event) {
  54816. BABYLON.Tools.Error("error on XHR request.");
  54817. callback();
  54818. }, false);
  54819. xhr.send();
  54820. }
  54821. else {
  54822. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54823. callback();
  54824. }
  54825. };
  54826. Database.IsUASupportingBlobStorage = true;
  54827. Database.IDBStorageEnabled = true;
  54828. Database.parseURL = function (url) {
  54829. var a = document.createElement('a');
  54830. a.href = url;
  54831. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54832. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54833. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54834. return absLocation;
  54835. };
  54836. Database.ReturnFullUrlLocation = function (url) {
  54837. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54838. return (Database.parseURL(window.location.href) + url);
  54839. }
  54840. else {
  54841. return url;
  54842. }
  54843. };
  54844. return Database;
  54845. }());
  54846. BABYLON.Database = Database;
  54847. })(BABYLON || (BABYLON = {}));
  54848. //# sourceMappingURL=babylon.database.js.map
  54849. var BABYLON;
  54850. (function (BABYLON) {
  54851. var FresnelParameters = /** @class */ (function () {
  54852. function FresnelParameters() {
  54853. this._isEnabled = true;
  54854. this.leftColor = BABYLON.Color3.White();
  54855. this.rightColor = BABYLON.Color3.Black();
  54856. this.bias = 0;
  54857. this.power = 1;
  54858. }
  54859. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54860. get: function () {
  54861. return this._isEnabled;
  54862. },
  54863. set: function (value) {
  54864. if (this._isEnabled === value) {
  54865. return;
  54866. }
  54867. this._isEnabled = value;
  54868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54869. },
  54870. enumerable: true,
  54871. configurable: true
  54872. });
  54873. FresnelParameters.prototype.clone = function () {
  54874. var newFresnelParameters = new FresnelParameters();
  54875. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54876. return newFresnelParameters;
  54877. };
  54878. FresnelParameters.prototype.serialize = function () {
  54879. var serializationObject = {};
  54880. serializationObject.isEnabled = this.isEnabled;
  54881. serializationObject.leftColor = this.leftColor;
  54882. serializationObject.rightColor = this.rightColor;
  54883. serializationObject.bias = this.bias;
  54884. serializationObject.power = this.power;
  54885. return serializationObject;
  54886. };
  54887. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54888. var fresnelParameters = new FresnelParameters();
  54889. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54890. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54891. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54892. fresnelParameters.bias = parsedFresnelParameters.bias;
  54893. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54894. return fresnelParameters;
  54895. };
  54896. return FresnelParameters;
  54897. }());
  54898. BABYLON.FresnelParameters = FresnelParameters;
  54899. })(BABYLON || (BABYLON = {}));
  54900. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54901. var BABYLON;
  54902. (function (BABYLON) {
  54903. var MultiMaterial = /** @class */ (function (_super) {
  54904. __extends(MultiMaterial, _super);
  54905. function MultiMaterial(name, scene) {
  54906. var _this = _super.call(this, name, scene, true) || this;
  54907. scene.multiMaterials.push(_this);
  54908. _this.subMaterials = new Array();
  54909. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54910. return _this;
  54911. }
  54912. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54913. get: function () {
  54914. return this._subMaterials;
  54915. },
  54916. set: function (value) {
  54917. this._subMaterials = value;
  54918. this._hookArray(value);
  54919. },
  54920. enumerable: true,
  54921. configurable: true
  54922. });
  54923. MultiMaterial.prototype._hookArray = function (array) {
  54924. var _this = this;
  54925. var oldPush = array.push;
  54926. array.push = function () {
  54927. var items = [];
  54928. for (var _i = 0; _i < arguments.length; _i++) {
  54929. items[_i] = arguments[_i];
  54930. }
  54931. var result = oldPush.apply(array, items);
  54932. _this._markAllSubMeshesAsTexturesDirty();
  54933. return result;
  54934. };
  54935. var oldSplice = array.splice;
  54936. array.splice = function (index, deleteCount) {
  54937. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54938. _this._markAllSubMeshesAsTexturesDirty();
  54939. return deleted;
  54940. };
  54941. };
  54942. // Properties
  54943. MultiMaterial.prototype.getSubMaterial = function (index) {
  54944. if (index < 0 || index >= this.subMaterials.length) {
  54945. return this.getScene().defaultMaterial;
  54946. }
  54947. return this.subMaterials[index];
  54948. };
  54949. MultiMaterial.prototype.getActiveTextures = function () {
  54950. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54951. if (subMaterial) {
  54952. return subMaterial.getActiveTextures();
  54953. }
  54954. else {
  54955. return [];
  54956. }
  54957. }));
  54958. var _a;
  54959. };
  54960. // Methods
  54961. MultiMaterial.prototype.getClassName = function () {
  54962. return "MultiMaterial";
  54963. };
  54964. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54965. for (var index = 0; index < this.subMaterials.length; index++) {
  54966. var subMaterial = this.subMaterials[index];
  54967. if (subMaterial) {
  54968. if (subMaterial.storeEffectOnSubMeshes) {
  54969. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54970. return false;
  54971. }
  54972. continue;
  54973. }
  54974. if (!subMaterial.isReady(mesh)) {
  54975. return false;
  54976. }
  54977. }
  54978. }
  54979. return true;
  54980. };
  54981. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54982. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54983. for (var index = 0; index < this.subMaterials.length; index++) {
  54984. var subMaterial = null;
  54985. var current = this.subMaterials[index];
  54986. if (cloneChildren && current) {
  54987. subMaterial = current.clone(name + "-" + current.name);
  54988. }
  54989. else {
  54990. subMaterial = this.subMaterials[index];
  54991. }
  54992. newMultiMaterial.subMaterials.push(subMaterial);
  54993. }
  54994. return newMultiMaterial;
  54995. };
  54996. MultiMaterial.prototype.serialize = function () {
  54997. var serializationObject = {};
  54998. serializationObject.name = this.name;
  54999. serializationObject.id = this.id;
  55000. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55001. serializationObject.materials = [];
  55002. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55003. var subMat = this.subMaterials[matIndex];
  55004. if (subMat) {
  55005. serializationObject.materials.push(subMat.id);
  55006. }
  55007. else {
  55008. serializationObject.materials.push(null);
  55009. }
  55010. }
  55011. return serializationObject;
  55012. };
  55013. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55014. var scene = this.getScene();
  55015. if (!scene) {
  55016. return;
  55017. }
  55018. var index = scene.multiMaterials.indexOf(this);
  55019. if (index >= 0) {
  55020. scene.multiMaterials.splice(index, 1);
  55021. }
  55022. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55023. };
  55024. return MultiMaterial;
  55025. }(BABYLON.Material));
  55026. BABYLON.MultiMaterial = MultiMaterial;
  55027. })(BABYLON || (BABYLON = {}));
  55028. //# sourceMappingURL=babylon.multiMaterial.js.map
  55029. var BABYLON;
  55030. (function (BABYLON) {
  55031. var FreeCameraTouchInput = /** @class */ (function () {
  55032. function FreeCameraTouchInput() {
  55033. this._offsetX = null;
  55034. this._offsetY = null;
  55035. this._pointerPressed = new Array();
  55036. this.touchAngularSensibility = 200000.0;
  55037. this.touchMoveSensibility = 250.0;
  55038. }
  55039. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55040. var _this = this;
  55041. var previousPosition = null;
  55042. if (this._pointerInput === undefined) {
  55043. this._onLostFocus = function (evt) {
  55044. _this._offsetX = null;
  55045. _this._offsetY = null;
  55046. };
  55047. this._pointerInput = function (p, s) {
  55048. var evt = p.event;
  55049. if (evt.pointerType === "mouse") {
  55050. return;
  55051. }
  55052. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55053. if (!noPreventDefault) {
  55054. evt.preventDefault();
  55055. }
  55056. _this._pointerPressed.push(evt.pointerId);
  55057. if (_this._pointerPressed.length !== 1) {
  55058. return;
  55059. }
  55060. previousPosition = {
  55061. x: evt.clientX,
  55062. y: evt.clientY
  55063. };
  55064. }
  55065. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55066. if (!noPreventDefault) {
  55067. evt.preventDefault();
  55068. }
  55069. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55070. if (index === -1) {
  55071. return;
  55072. }
  55073. _this._pointerPressed.splice(index, 1);
  55074. if (index != 0) {
  55075. return;
  55076. }
  55077. previousPosition = null;
  55078. _this._offsetX = null;
  55079. _this._offsetY = null;
  55080. }
  55081. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55082. if (!noPreventDefault) {
  55083. evt.preventDefault();
  55084. }
  55085. if (!previousPosition) {
  55086. return;
  55087. }
  55088. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55089. if (index != 0) {
  55090. return;
  55091. }
  55092. _this._offsetX = evt.clientX - previousPosition.x;
  55093. _this._offsetY = -(evt.clientY - previousPosition.y);
  55094. }
  55095. };
  55096. }
  55097. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55098. if (this._onLostFocus) {
  55099. element.addEventListener("blur", this._onLostFocus);
  55100. }
  55101. };
  55102. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55103. if (this._pointerInput && element) {
  55104. if (this._observer) {
  55105. this.camera.getScene().onPointerObservable.remove(this._observer);
  55106. this._observer = null;
  55107. }
  55108. if (this._onLostFocus) {
  55109. element.removeEventListener("blur", this._onLostFocus);
  55110. this._onLostFocus = null;
  55111. }
  55112. this._pointerPressed = [];
  55113. this._offsetX = null;
  55114. this._offsetY = null;
  55115. }
  55116. };
  55117. FreeCameraTouchInput.prototype.checkInputs = function () {
  55118. if (this._offsetX && this._offsetY) {
  55119. var camera = this.camera;
  55120. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55121. if (this._pointerPressed.length > 1) {
  55122. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55123. }
  55124. else {
  55125. var speed = camera._computeLocalCameraSpeed();
  55126. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55127. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55128. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55129. }
  55130. }
  55131. };
  55132. FreeCameraTouchInput.prototype.getClassName = function () {
  55133. return "FreeCameraTouchInput";
  55134. };
  55135. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55136. return "touch";
  55137. };
  55138. __decorate([
  55139. BABYLON.serialize()
  55140. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55141. __decorate([
  55142. BABYLON.serialize()
  55143. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55144. return FreeCameraTouchInput;
  55145. }());
  55146. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55147. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55148. })(BABYLON || (BABYLON = {}));
  55149. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55150. var BABYLON;
  55151. (function (BABYLON) {
  55152. // We're mainly based on the logic defined into the FreeCamera code
  55153. var TouchCamera = /** @class */ (function (_super) {
  55154. __extends(TouchCamera, _super);
  55155. //-- end properties for backward compatibility for inputs
  55156. function TouchCamera(name, position, scene) {
  55157. var _this = _super.call(this, name, position, scene) || this;
  55158. _this.inputs.addTouch();
  55159. _this._setupInputs();
  55160. return _this;
  55161. }
  55162. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55163. //-- Begin properties for backward compatibility for inputs
  55164. get: function () {
  55165. var touch = this.inputs.attached["touch"];
  55166. if (touch)
  55167. return touch.touchAngularSensibility;
  55168. return 0;
  55169. },
  55170. set: function (value) {
  55171. var touch = this.inputs.attached["touch"];
  55172. if (touch)
  55173. touch.touchAngularSensibility = value;
  55174. },
  55175. enumerable: true,
  55176. configurable: true
  55177. });
  55178. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55179. get: function () {
  55180. var touch = this.inputs.attached["touch"];
  55181. if (touch)
  55182. return touch.touchMoveSensibility;
  55183. return 0;
  55184. },
  55185. set: function (value) {
  55186. var touch = this.inputs.attached["touch"];
  55187. if (touch)
  55188. touch.touchMoveSensibility = value;
  55189. },
  55190. enumerable: true,
  55191. configurable: true
  55192. });
  55193. TouchCamera.prototype.getClassName = function () {
  55194. return "TouchCamera";
  55195. };
  55196. TouchCamera.prototype._setupInputs = function () {
  55197. var mouse = this.inputs.attached["mouse"];
  55198. if (mouse) {
  55199. mouse.touchEnabled = false;
  55200. }
  55201. };
  55202. return TouchCamera;
  55203. }(BABYLON.FreeCamera));
  55204. BABYLON.TouchCamera = TouchCamera;
  55205. })(BABYLON || (BABYLON = {}));
  55206. //# sourceMappingURL=babylon.touchCamera.js.map
  55207. var BABYLON;
  55208. (function (BABYLON) {
  55209. var ProceduralTexture = /** @class */ (function (_super) {
  55210. __extends(ProceduralTexture, _super);
  55211. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55212. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55213. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55214. if (isCube === void 0) { isCube = false; }
  55215. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55216. _this.isCube = isCube;
  55217. _this.isEnabled = true;
  55218. _this._currentRefreshId = -1;
  55219. _this._refreshRate = 1;
  55220. _this._vertexBuffers = {};
  55221. _this._uniforms = new Array();
  55222. _this._samplers = new Array();
  55223. _this._textures = {};
  55224. _this._floats = {};
  55225. _this._floatsArrays = {};
  55226. _this._colors3 = {};
  55227. _this._colors4 = {};
  55228. _this._vectors2 = {};
  55229. _this._vectors3 = {};
  55230. _this._matrices = {};
  55231. _this._fallbackTextureUsed = false;
  55232. scene._proceduralTextures.push(_this);
  55233. _this._engine = scene.getEngine();
  55234. _this.name = name;
  55235. _this.isRenderTarget = true;
  55236. _this._size = size;
  55237. _this._generateMipMaps = generateMipMaps;
  55238. _this.setFragment(fragment);
  55239. _this._fallbackTexture = fallbackTexture;
  55240. if (isCube) {
  55241. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55242. _this.setFloat("face", 0);
  55243. }
  55244. else {
  55245. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55246. }
  55247. // VBO
  55248. var vertices = [];
  55249. vertices.push(1, 1);
  55250. vertices.push(-1, 1);
  55251. vertices.push(-1, -1);
  55252. vertices.push(1, -1);
  55253. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55254. _this._createIndexBuffer();
  55255. return _this;
  55256. }
  55257. ProceduralTexture.prototype._createIndexBuffer = function () {
  55258. var engine = this._engine;
  55259. // Indices
  55260. var indices = [];
  55261. indices.push(0);
  55262. indices.push(1);
  55263. indices.push(2);
  55264. indices.push(0);
  55265. indices.push(2);
  55266. indices.push(3);
  55267. this._indexBuffer = engine.createIndexBuffer(indices);
  55268. };
  55269. ProceduralTexture.prototype._rebuild = function () {
  55270. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55271. if (vb) {
  55272. vb._rebuild();
  55273. }
  55274. this._createIndexBuffer();
  55275. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55276. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55277. }
  55278. };
  55279. ProceduralTexture.prototype.reset = function () {
  55280. if (this._effect === undefined) {
  55281. return;
  55282. }
  55283. var engine = this._engine;
  55284. engine._releaseEffect(this._effect);
  55285. };
  55286. ProceduralTexture.prototype.isReady = function () {
  55287. var _this = this;
  55288. var engine = this._engine;
  55289. var shaders;
  55290. if (!this._fragment) {
  55291. return false;
  55292. }
  55293. if (this._fallbackTextureUsed) {
  55294. return true;
  55295. }
  55296. if (this._fragment.fragmentElement !== undefined) {
  55297. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55298. }
  55299. else {
  55300. shaders = { vertex: "procedural", fragment: this._fragment };
  55301. }
  55302. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55303. _this.releaseInternalTexture();
  55304. if (_this._fallbackTexture) {
  55305. _this._texture = _this._fallbackTexture._texture;
  55306. if (_this._texture) {
  55307. _this._texture.incrementReferences();
  55308. }
  55309. }
  55310. _this._fallbackTextureUsed = true;
  55311. });
  55312. return this._effect.isReady();
  55313. };
  55314. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55315. this._currentRefreshId = -1;
  55316. };
  55317. ProceduralTexture.prototype.setFragment = function (fragment) {
  55318. this._fragment = fragment;
  55319. };
  55320. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55321. get: function () {
  55322. return this._refreshRate;
  55323. },
  55324. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55325. set: function (value) {
  55326. this._refreshRate = value;
  55327. this.resetRefreshCounter();
  55328. },
  55329. enumerable: true,
  55330. configurable: true
  55331. });
  55332. ProceduralTexture.prototype._shouldRender = function () {
  55333. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55334. return false;
  55335. }
  55336. if (this._fallbackTextureUsed) {
  55337. return false;
  55338. }
  55339. if (this._currentRefreshId === -1) {
  55340. this._currentRefreshId = 1;
  55341. return true;
  55342. }
  55343. if (this.refreshRate === this._currentRefreshId) {
  55344. this._currentRefreshId = 1;
  55345. return true;
  55346. }
  55347. this._currentRefreshId++;
  55348. return false;
  55349. };
  55350. ProceduralTexture.prototype.getRenderSize = function () {
  55351. return this._size;
  55352. };
  55353. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55354. if (this._fallbackTextureUsed) {
  55355. return;
  55356. }
  55357. this.releaseInternalTexture();
  55358. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55359. };
  55360. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55361. if (this._uniforms.indexOf(uniformName) === -1) {
  55362. this._uniforms.push(uniformName);
  55363. }
  55364. };
  55365. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55366. if (this._samplers.indexOf(name) === -1) {
  55367. this._samplers.push(name);
  55368. }
  55369. this._textures[name] = texture;
  55370. return this;
  55371. };
  55372. ProceduralTexture.prototype.setFloat = function (name, value) {
  55373. this._checkUniform(name);
  55374. this._floats[name] = value;
  55375. return this;
  55376. };
  55377. ProceduralTexture.prototype.setFloats = function (name, value) {
  55378. this._checkUniform(name);
  55379. this._floatsArrays[name] = value;
  55380. return this;
  55381. };
  55382. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55383. this._checkUniform(name);
  55384. this._colors3[name] = value;
  55385. return this;
  55386. };
  55387. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55388. this._checkUniform(name);
  55389. this._colors4[name] = value;
  55390. return this;
  55391. };
  55392. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55393. this._checkUniform(name);
  55394. this._vectors2[name] = value;
  55395. return this;
  55396. };
  55397. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55398. this._checkUniform(name);
  55399. this._vectors3[name] = value;
  55400. return this;
  55401. };
  55402. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55403. this._checkUniform(name);
  55404. this._matrices[name] = value;
  55405. return this;
  55406. };
  55407. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55408. var scene = this.getScene();
  55409. if (!scene) {
  55410. return;
  55411. }
  55412. var engine = this._engine;
  55413. // Render
  55414. engine.enableEffect(this._effect);
  55415. engine.setState(false);
  55416. // Texture
  55417. for (var name in this._textures) {
  55418. this._effect.setTexture(name, this._textures[name]);
  55419. }
  55420. // Float
  55421. for (name in this._floats) {
  55422. this._effect.setFloat(name, this._floats[name]);
  55423. }
  55424. // Floats
  55425. for (name in this._floatsArrays) {
  55426. this._effect.setArray(name, this._floatsArrays[name]);
  55427. }
  55428. // Color3
  55429. for (name in this._colors3) {
  55430. this._effect.setColor3(name, this._colors3[name]);
  55431. }
  55432. // Color4
  55433. for (name in this._colors4) {
  55434. var color = this._colors4[name];
  55435. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55436. }
  55437. // Vector2
  55438. for (name in this._vectors2) {
  55439. this._effect.setVector2(name, this._vectors2[name]);
  55440. }
  55441. // Vector3
  55442. for (name in this._vectors3) {
  55443. this._effect.setVector3(name, this._vectors3[name]);
  55444. }
  55445. // Matrix
  55446. for (name in this._matrices) {
  55447. this._effect.setMatrix(name, this._matrices[name]);
  55448. }
  55449. if (!this._texture) {
  55450. return;
  55451. }
  55452. if (this.isCube) {
  55453. for (var face = 0; face < 6; face++) {
  55454. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55455. // VBOs
  55456. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55457. this._effect.setFloat("face", face);
  55458. // Clear
  55459. engine.clear(scene.clearColor, true, true, true);
  55460. // Draw order
  55461. engine.draw(true, 0, 6);
  55462. // Mipmaps
  55463. if (face === 5) {
  55464. engine.generateMipMapsForCubemap(this._texture);
  55465. }
  55466. }
  55467. }
  55468. else {
  55469. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55470. // VBOs
  55471. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55472. // Clear
  55473. engine.clear(scene.clearColor, true, true, true);
  55474. // Draw order
  55475. engine.draw(true, 0, 6);
  55476. }
  55477. // Unbind
  55478. engine.unBindFramebuffer(this._texture, this.isCube);
  55479. if (this.onGenerated) {
  55480. this.onGenerated();
  55481. }
  55482. };
  55483. ProceduralTexture.prototype.clone = function () {
  55484. var textureSize = this.getSize();
  55485. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55486. // Base texture
  55487. newTexture.hasAlpha = this.hasAlpha;
  55488. newTexture.level = this.level;
  55489. // RenderTarget Texture
  55490. newTexture.coordinatesMode = this.coordinatesMode;
  55491. return newTexture;
  55492. };
  55493. ProceduralTexture.prototype.dispose = function () {
  55494. var scene = this.getScene();
  55495. if (!scene) {
  55496. return;
  55497. }
  55498. var index = scene._proceduralTextures.indexOf(this);
  55499. if (index >= 0) {
  55500. scene._proceduralTextures.splice(index, 1);
  55501. }
  55502. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55503. if (vertexBuffer) {
  55504. vertexBuffer.dispose();
  55505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55506. }
  55507. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55508. this._indexBuffer = null;
  55509. }
  55510. _super.prototype.dispose.call(this);
  55511. };
  55512. return ProceduralTexture;
  55513. }(BABYLON.Texture));
  55514. BABYLON.ProceduralTexture = ProceduralTexture;
  55515. })(BABYLON || (BABYLON = {}));
  55516. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55517. var BABYLON;
  55518. (function (BABYLON) {
  55519. var CustomProceduralTexture = /** @class */ (function (_super) {
  55520. __extends(CustomProceduralTexture, _super);
  55521. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55522. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55523. _this._animate = true;
  55524. _this._time = 0;
  55525. _this._texturePath = texturePath;
  55526. //Try to load json
  55527. _this.loadJson(texturePath);
  55528. _this.refreshRate = 1;
  55529. return _this;
  55530. }
  55531. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55532. var _this = this;
  55533. var noConfigFile = function () {
  55534. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55535. try {
  55536. _this.setFragment(_this._texturePath);
  55537. }
  55538. catch (ex) {
  55539. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55540. }
  55541. };
  55542. var configFileUrl = jsonUrl + "/config.json";
  55543. var xhr = new XMLHttpRequest();
  55544. xhr.open("GET", configFileUrl, true);
  55545. xhr.addEventListener("load", function () {
  55546. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55547. try {
  55548. _this._config = JSON.parse(xhr.response);
  55549. _this.updateShaderUniforms();
  55550. _this.updateTextures();
  55551. _this.setFragment(_this._texturePath + "/custom");
  55552. _this._animate = _this._config.animate;
  55553. _this.refreshRate = _this._config.refreshrate;
  55554. }
  55555. catch (ex) {
  55556. noConfigFile();
  55557. }
  55558. }
  55559. else {
  55560. noConfigFile();
  55561. }
  55562. }, false);
  55563. xhr.addEventListener("error", function () {
  55564. noConfigFile();
  55565. }, false);
  55566. try {
  55567. xhr.send();
  55568. }
  55569. catch (ex) {
  55570. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55571. }
  55572. };
  55573. CustomProceduralTexture.prototype.isReady = function () {
  55574. if (!_super.prototype.isReady.call(this)) {
  55575. return false;
  55576. }
  55577. for (var name in this._textures) {
  55578. var texture = this._textures[name];
  55579. if (!texture.isReady()) {
  55580. return false;
  55581. }
  55582. }
  55583. return true;
  55584. };
  55585. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55586. var scene = this.getScene();
  55587. if (this._animate && scene) {
  55588. this._time += scene.getAnimationRatio() * 0.03;
  55589. this.updateShaderUniforms();
  55590. }
  55591. _super.prototype.render.call(this, useCameraPostProcess);
  55592. };
  55593. CustomProceduralTexture.prototype.updateTextures = function () {
  55594. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55595. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55596. }
  55597. };
  55598. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55599. if (this._config) {
  55600. for (var j = 0; j < this._config.uniforms.length; j++) {
  55601. var uniform = this._config.uniforms[j];
  55602. switch (uniform.type) {
  55603. case "float":
  55604. this.setFloat(uniform.name, uniform.value);
  55605. break;
  55606. case "color3":
  55607. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55608. break;
  55609. case "color4":
  55610. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55611. break;
  55612. case "vector2":
  55613. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55614. break;
  55615. case "vector3":
  55616. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55617. break;
  55618. }
  55619. }
  55620. }
  55621. this.setFloat("time", this._time);
  55622. };
  55623. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55624. get: function () {
  55625. return this._animate;
  55626. },
  55627. set: function (value) {
  55628. this._animate = value;
  55629. },
  55630. enumerable: true,
  55631. configurable: true
  55632. });
  55633. return CustomProceduralTexture;
  55634. }(BABYLON.ProceduralTexture));
  55635. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55636. })(BABYLON || (BABYLON = {}));
  55637. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55638. var BABYLON;
  55639. (function (BABYLON) {
  55640. var FreeCameraGamepadInput = /** @class */ (function () {
  55641. function FreeCameraGamepadInput() {
  55642. this.gamepadAngularSensibility = 200;
  55643. this.gamepadMoveSensibility = 40;
  55644. // private members
  55645. this._cameraTransform = BABYLON.Matrix.Identity();
  55646. this._deltaTransform = BABYLON.Vector3.Zero();
  55647. this._vector3 = BABYLON.Vector3.Zero();
  55648. this._vector2 = BABYLON.Vector2.Zero();
  55649. }
  55650. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55651. var _this = this;
  55652. var manager = this.camera.getScene().gamepadManager;
  55653. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55654. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55655. // prioritize XBOX gamepads.
  55656. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55657. _this.gamepad = gamepad;
  55658. }
  55659. }
  55660. });
  55661. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55662. if (_this.gamepad === gamepad) {
  55663. _this.gamepad = null;
  55664. }
  55665. });
  55666. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55667. };
  55668. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55669. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55670. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55671. this.gamepad = null;
  55672. };
  55673. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55674. if (this.gamepad && this.gamepad.leftStick) {
  55675. var camera = this.camera;
  55676. var LSValues = this.gamepad.leftStick;
  55677. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55678. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55679. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55680. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55681. var RSValues = this.gamepad.rightStick;
  55682. if (RSValues) {
  55683. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55684. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55685. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55686. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55687. }
  55688. else {
  55689. RSValues = { x: 0, y: 0 };
  55690. }
  55691. if (!camera.rotationQuaternion) {
  55692. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55693. }
  55694. else {
  55695. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55696. }
  55697. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55698. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55699. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55700. camera.cameraDirection.addInPlace(this._deltaTransform);
  55701. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55702. camera.cameraRotation.addInPlace(this._vector2);
  55703. }
  55704. };
  55705. FreeCameraGamepadInput.prototype.getClassName = function () {
  55706. return "FreeCameraGamepadInput";
  55707. };
  55708. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55709. return "gamepad";
  55710. };
  55711. __decorate([
  55712. BABYLON.serialize()
  55713. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55714. __decorate([
  55715. BABYLON.serialize()
  55716. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55717. return FreeCameraGamepadInput;
  55718. }());
  55719. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55720. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55721. })(BABYLON || (BABYLON = {}));
  55722. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55723. var BABYLON;
  55724. (function (BABYLON) {
  55725. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55726. function ArcRotateCameraGamepadInput() {
  55727. this.gamepadRotationSensibility = 80;
  55728. this.gamepadMoveSensibility = 40;
  55729. }
  55730. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55731. var _this = this;
  55732. var manager = this.camera.getScene().gamepadManager;
  55733. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55734. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55735. // prioritize XBOX gamepads.
  55736. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55737. _this.gamepad = gamepad;
  55738. }
  55739. }
  55740. });
  55741. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55742. if (_this.gamepad === gamepad) {
  55743. _this.gamepad = null;
  55744. }
  55745. });
  55746. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55747. };
  55748. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55749. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55750. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55751. this.gamepad = null;
  55752. };
  55753. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55754. if (this.gamepad) {
  55755. var camera = this.camera;
  55756. var RSValues = this.gamepad.rightStick;
  55757. if (RSValues) {
  55758. if (RSValues.x != 0) {
  55759. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55760. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55761. camera.inertialAlphaOffset += normalizedRX;
  55762. }
  55763. }
  55764. if (RSValues.y != 0) {
  55765. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55766. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55767. camera.inertialBetaOffset += normalizedRY;
  55768. }
  55769. }
  55770. }
  55771. var LSValues = this.gamepad.leftStick;
  55772. if (LSValues && LSValues.y != 0) {
  55773. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55774. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55775. this.camera.inertialRadiusOffset -= normalizedLY;
  55776. }
  55777. }
  55778. }
  55779. };
  55780. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55781. return "ArcRotateCameraGamepadInput";
  55782. };
  55783. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55784. return "gamepad";
  55785. };
  55786. __decorate([
  55787. BABYLON.serialize()
  55788. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55789. __decorate([
  55790. BABYLON.serialize()
  55791. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55792. return ArcRotateCameraGamepadInput;
  55793. }());
  55794. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55795. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55796. })(BABYLON || (BABYLON = {}));
  55797. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55798. var BABYLON;
  55799. (function (BABYLON) {
  55800. var GamepadManager = /** @class */ (function () {
  55801. function GamepadManager(_scene) {
  55802. var _this = this;
  55803. this._scene = _scene;
  55804. this._babylonGamepads = [];
  55805. this._oneGamepadConnected = false;
  55806. this._isMonitoring = false;
  55807. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55808. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55809. this._gamepadEventSupported = false;
  55810. }
  55811. else {
  55812. this._gamepadEventSupported = 'GamepadEvent' in window;
  55813. this._gamepadSupport = (navigator.getGamepads ||
  55814. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55815. }
  55816. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55817. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55818. for (var i in _this._babylonGamepads) {
  55819. var gamepad = _this._babylonGamepads[i];
  55820. if (gamepad && gamepad._isConnected) {
  55821. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55822. }
  55823. }
  55824. });
  55825. this._onGamepadConnectedEvent = function (evt) {
  55826. var gamepad = evt.gamepad;
  55827. if (gamepad.index in _this._babylonGamepads) {
  55828. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55829. return;
  55830. }
  55831. }
  55832. var newGamepad;
  55833. if (_this._babylonGamepads[gamepad.index]) {
  55834. newGamepad = _this._babylonGamepads[gamepad.index];
  55835. newGamepad.browserGamepad = gamepad;
  55836. newGamepad._isConnected = true;
  55837. }
  55838. else {
  55839. newGamepad = _this._addNewGamepad(gamepad);
  55840. }
  55841. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55842. _this._startMonitoringGamepads();
  55843. };
  55844. this._onGamepadDisconnectedEvent = function (evt) {
  55845. var gamepad = evt.gamepad;
  55846. // Remove the gamepad from the list of gamepads to monitor.
  55847. for (var i in _this._babylonGamepads) {
  55848. if (_this._babylonGamepads[i].index === gamepad.index) {
  55849. var disconnectedGamepad = _this._babylonGamepads[i];
  55850. disconnectedGamepad._isConnected = false;
  55851. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55852. break;
  55853. }
  55854. }
  55855. };
  55856. if (this._gamepadSupport) {
  55857. //first add already-connected gamepads
  55858. this._updateGamepadObjects();
  55859. if (this._babylonGamepads.length) {
  55860. this._startMonitoringGamepads();
  55861. }
  55862. // Checking if the gamepad connected event is supported (like in Firefox)
  55863. if (this._gamepadEventSupported) {
  55864. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55865. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55866. }
  55867. else {
  55868. this._startMonitoringGamepads();
  55869. }
  55870. }
  55871. }
  55872. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55873. get: function () {
  55874. return this._babylonGamepads;
  55875. },
  55876. enumerable: true,
  55877. configurable: true
  55878. });
  55879. GamepadManager.prototype.getGamepadByType = function (type) {
  55880. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55881. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55882. var gamepad = _a[_i];
  55883. if (gamepad && gamepad.type === type) {
  55884. return gamepad;
  55885. }
  55886. }
  55887. return null;
  55888. };
  55889. GamepadManager.prototype.dispose = function () {
  55890. if (this._gamepadEventSupported) {
  55891. if (this._onGamepadConnectedEvent) {
  55892. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55893. }
  55894. if (this._onGamepadDisconnectedEvent) {
  55895. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55896. }
  55897. this._onGamepadConnectedEvent = null;
  55898. this._onGamepadDisconnectedEvent = null;
  55899. }
  55900. this._babylonGamepads.forEach(function (gamepad) {
  55901. gamepad.dispose();
  55902. });
  55903. this.onGamepadConnectedObservable.clear();
  55904. this.onGamepadDisconnectedObservable.clear();
  55905. this._oneGamepadConnected = false;
  55906. this._stopMonitoringGamepads();
  55907. this._babylonGamepads = [];
  55908. };
  55909. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55910. if (!this._oneGamepadConnected) {
  55911. this._oneGamepadConnected = true;
  55912. }
  55913. var newGamepad;
  55914. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55915. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55916. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55917. }
  55918. else if (gamepad.pose) {
  55919. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55920. }
  55921. else {
  55922. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55923. }
  55924. this._babylonGamepads[newGamepad.index] = newGamepad;
  55925. return newGamepad;
  55926. };
  55927. GamepadManager.prototype._startMonitoringGamepads = function () {
  55928. if (!this._isMonitoring) {
  55929. this._isMonitoring = true;
  55930. //back-comp
  55931. if (!this._scene) {
  55932. this._checkGamepadsStatus();
  55933. }
  55934. }
  55935. };
  55936. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55937. this._isMonitoring = false;
  55938. };
  55939. GamepadManager.prototype._checkGamepadsStatus = function () {
  55940. var _this = this;
  55941. // Hack to be compatible Chrome
  55942. this._updateGamepadObjects();
  55943. for (var i in this._babylonGamepads) {
  55944. var gamepad = this._babylonGamepads[i];
  55945. if (!gamepad || !gamepad.isConnected) {
  55946. continue;
  55947. }
  55948. gamepad.update();
  55949. }
  55950. if (this._isMonitoring && !this._scene) {
  55951. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55952. }
  55953. };
  55954. // This function is called only on Chrome, which does not properly support
  55955. // connection/disconnection events and forces you to recopy again the gamepad object
  55956. GamepadManager.prototype._updateGamepadObjects = function () {
  55957. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55958. for (var i = 0; i < gamepads.length; i++) {
  55959. if (gamepads[i]) {
  55960. if (!this._babylonGamepads[gamepads[i].index]) {
  55961. var newGamepad = this._addNewGamepad(gamepads[i]);
  55962. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55963. }
  55964. else {
  55965. // Forced to copy again this object for Chrome for unknown reason
  55966. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55967. if (!this._babylonGamepads[i].isConnected) {
  55968. this._babylonGamepads[i]._isConnected = true;
  55969. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55970. }
  55971. }
  55972. }
  55973. }
  55974. };
  55975. return GamepadManager;
  55976. }());
  55977. BABYLON.GamepadManager = GamepadManager;
  55978. })(BABYLON || (BABYLON = {}));
  55979. //# sourceMappingURL=babylon.gamepadManager.js.map
  55980. var BABYLON;
  55981. (function (BABYLON) {
  55982. var StickValues = /** @class */ (function () {
  55983. function StickValues(x, y) {
  55984. this.x = x;
  55985. this.y = y;
  55986. }
  55987. return StickValues;
  55988. }());
  55989. BABYLON.StickValues = StickValues;
  55990. var Gamepad = /** @class */ (function () {
  55991. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55992. if (leftStickX === void 0) { leftStickX = 0; }
  55993. if (leftStickY === void 0) { leftStickY = 1; }
  55994. if (rightStickX === void 0) { rightStickX = 2; }
  55995. if (rightStickY === void 0) { rightStickY = 3; }
  55996. this.id = id;
  55997. this.index = index;
  55998. this.browserGamepad = browserGamepad;
  55999. this._isConnected = true;
  56000. this.type = Gamepad.GAMEPAD;
  56001. this._leftStickAxisX = leftStickX;
  56002. this._leftStickAxisY = leftStickY;
  56003. this._rightStickAxisX = rightStickX;
  56004. this._rightStickAxisY = rightStickY;
  56005. if (this.browserGamepad.axes.length >= 2) {
  56006. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56007. }
  56008. if (this.browserGamepad.axes.length >= 4) {
  56009. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56010. }
  56011. }
  56012. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56013. get: function () {
  56014. return this._isConnected;
  56015. },
  56016. enumerable: true,
  56017. configurable: true
  56018. });
  56019. Gamepad.prototype.onleftstickchanged = function (callback) {
  56020. this._onleftstickchanged = callback;
  56021. };
  56022. Gamepad.prototype.onrightstickchanged = function (callback) {
  56023. this._onrightstickchanged = callback;
  56024. };
  56025. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56026. get: function () {
  56027. return this._leftStick;
  56028. },
  56029. set: function (newValues) {
  56030. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56031. this._onleftstickchanged(newValues);
  56032. }
  56033. this._leftStick = newValues;
  56034. },
  56035. enumerable: true,
  56036. configurable: true
  56037. });
  56038. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56039. get: function () {
  56040. return this._rightStick;
  56041. },
  56042. set: function (newValues) {
  56043. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56044. this._onrightstickchanged(newValues);
  56045. }
  56046. this._rightStick = newValues;
  56047. },
  56048. enumerable: true,
  56049. configurable: true
  56050. });
  56051. Gamepad.prototype.update = function () {
  56052. if (this._leftStick) {
  56053. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56054. }
  56055. if (this._rightStick) {
  56056. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56057. }
  56058. };
  56059. Gamepad.prototype.dispose = function () {
  56060. };
  56061. Gamepad.GAMEPAD = 0;
  56062. Gamepad.GENERIC = 1;
  56063. Gamepad.XBOX = 2;
  56064. Gamepad.POSE_ENABLED = 3;
  56065. return Gamepad;
  56066. }());
  56067. BABYLON.Gamepad = Gamepad;
  56068. var GenericPad = /** @class */ (function (_super) {
  56069. __extends(GenericPad, _super);
  56070. function GenericPad(id, index, browserGamepad) {
  56071. var _this = _super.call(this, id, index, browserGamepad) || this;
  56072. _this.onButtonDownObservable = new BABYLON.Observable();
  56073. _this.onButtonUpObservable = new BABYLON.Observable();
  56074. _this.type = Gamepad.GENERIC;
  56075. _this._buttons = new Array(browserGamepad.buttons.length);
  56076. return _this;
  56077. }
  56078. GenericPad.prototype.onbuttondown = function (callback) {
  56079. this._onbuttondown = callback;
  56080. };
  56081. GenericPad.prototype.onbuttonup = function (callback) {
  56082. this._onbuttonup = callback;
  56083. };
  56084. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56085. if (newValue !== currentValue) {
  56086. if (newValue === 1) {
  56087. if (this._onbuttondown) {
  56088. this._onbuttondown(buttonIndex);
  56089. }
  56090. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56091. }
  56092. if (newValue === 0) {
  56093. if (this._onbuttonup) {
  56094. this._onbuttonup(buttonIndex);
  56095. }
  56096. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56097. }
  56098. }
  56099. return newValue;
  56100. };
  56101. GenericPad.prototype.update = function () {
  56102. _super.prototype.update.call(this);
  56103. for (var index = 0; index < this._buttons.length; index++) {
  56104. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56105. }
  56106. };
  56107. return GenericPad;
  56108. }(Gamepad));
  56109. BABYLON.GenericPad = GenericPad;
  56110. })(BABYLON || (BABYLON = {}));
  56111. //# sourceMappingURL=babylon.gamepad.js.map
  56112. var BABYLON;
  56113. (function (BABYLON) {
  56114. var Xbox360Button;
  56115. (function (Xbox360Button) {
  56116. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56117. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56118. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56119. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56120. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56121. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56122. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56123. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56124. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56125. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56126. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56127. var Xbox360Dpad;
  56128. (function (Xbox360Dpad) {
  56129. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56130. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56131. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56132. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56133. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56134. var Xbox360Pad = /** @class */ (function (_super) {
  56135. __extends(Xbox360Pad, _super);
  56136. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56137. if (xboxOne === void 0) { xboxOne = false; }
  56138. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56139. _this._leftTrigger = 0;
  56140. _this._rightTrigger = 0;
  56141. _this.onButtonDownObservable = new BABYLON.Observable();
  56142. _this.onButtonUpObservable = new BABYLON.Observable();
  56143. _this.onPadDownObservable = new BABYLON.Observable();
  56144. _this.onPadUpObservable = new BABYLON.Observable();
  56145. _this._buttonA = 0;
  56146. _this._buttonB = 0;
  56147. _this._buttonX = 0;
  56148. _this._buttonY = 0;
  56149. _this._buttonBack = 0;
  56150. _this._buttonStart = 0;
  56151. _this._buttonLB = 0;
  56152. _this._buttonRB = 0;
  56153. _this._buttonLeftStick = 0;
  56154. _this._buttonRightStick = 0;
  56155. _this._dPadUp = 0;
  56156. _this._dPadDown = 0;
  56157. _this._dPadLeft = 0;
  56158. _this._dPadRight = 0;
  56159. _this._isXboxOnePad = false;
  56160. _this.type = BABYLON.Gamepad.XBOX;
  56161. _this._isXboxOnePad = xboxOne;
  56162. return _this;
  56163. }
  56164. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56165. this._onlefttriggerchanged = callback;
  56166. };
  56167. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56168. this._onrighttriggerchanged = callback;
  56169. };
  56170. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56171. get: function () {
  56172. return this._leftTrigger;
  56173. },
  56174. set: function (newValue) {
  56175. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56176. this._onlefttriggerchanged(newValue);
  56177. }
  56178. this._leftTrigger = newValue;
  56179. },
  56180. enumerable: true,
  56181. configurable: true
  56182. });
  56183. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56184. get: function () {
  56185. return this._rightTrigger;
  56186. },
  56187. set: function (newValue) {
  56188. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56189. this._onrighttriggerchanged(newValue);
  56190. }
  56191. this._rightTrigger = newValue;
  56192. },
  56193. enumerable: true,
  56194. configurable: true
  56195. });
  56196. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56197. this._onbuttondown = callback;
  56198. };
  56199. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56200. this._onbuttonup = callback;
  56201. };
  56202. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56203. this._ondpaddown = callback;
  56204. };
  56205. Xbox360Pad.prototype.ondpadup = function (callback) {
  56206. this._ondpadup = callback;
  56207. };
  56208. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56209. if (newValue !== currentValue) {
  56210. if (newValue === 1) {
  56211. if (this._onbuttondown) {
  56212. this._onbuttondown(buttonType);
  56213. }
  56214. this.onButtonDownObservable.notifyObservers(buttonType);
  56215. }
  56216. if (newValue === 0) {
  56217. if (this._onbuttonup) {
  56218. this._onbuttonup(buttonType);
  56219. }
  56220. this.onButtonUpObservable.notifyObservers(buttonType);
  56221. }
  56222. }
  56223. return newValue;
  56224. };
  56225. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56226. if (newValue !== currentValue) {
  56227. if (newValue === 1) {
  56228. if (this._ondpaddown) {
  56229. this._ondpaddown(buttonType);
  56230. }
  56231. this.onPadDownObservable.notifyObservers(buttonType);
  56232. }
  56233. if (newValue === 0) {
  56234. if (this._ondpadup) {
  56235. this._ondpadup(buttonType);
  56236. }
  56237. this.onPadUpObservable.notifyObservers(buttonType);
  56238. }
  56239. }
  56240. return newValue;
  56241. };
  56242. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56243. get: function () {
  56244. return this._buttonA;
  56245. },
  56246. set: function (value) {
  56247. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56248. },
  56249. enumerable: true,
  56250. configurable: true
  56251. });
  56252. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56253. get: function () {
  56254. return this._buttonB;
  56255. },
  56256. set: function (value) {
  56257. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56258. },
  56259. enumerable: true,
  56260. configurable: true
  56261. });
  56262. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56263. get: function () {
  56264. return this._buttonX;
  56265. },
  56266. set: function (value) {
  56267. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56268. },
  56269. enumerable: true,
  56270. configurable: true
  56271. });
  56272. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56273. get: function () {
  56274. return this._buttonY;
  56275. },
  56276. set: function (value) {
  56277. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56278. },
  56279. enumerable: true,
  56280. configurable: true
  56281. });
  56282. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56283. get: function () {
  56284. return this._buttonStart;
  56285. },
  56286. set: function (value) {
  56287. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56288. },
  56289. enumerable: true,
  56290. configurable: true
  56291. });
  56292. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56293. get: function () {
  56294. return this._buttonBack;
  56295. },
  56296. set: function (value) {
  56297. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56298. },
  56299. enumerable: true,
  56300. configurable: true
  56301. });
  56302. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56303. get: function () {
  56304. return this._buttonLB;
  56305. },
  56306. set: function (value) {
  56307. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56308. },
  56309. enumerable: true,
  56310. configurable: true
  56311. });
  56312. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56313. get: function () {
  56314. return this._buttonRB;
  56315. },
  56316. set: function (value) {
  56317. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56323. get: function () {
  56324. return this._buttonLeftStick;
  56325. },
  56326. set: function (value) {
  56327. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56333. get: function () {
  56334. return this._buttonRightStick;
  56335. },
  56336. set: function (value) {
  56337. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56338. },
  56339. enumerable: true,
  56340. configurable: true
  56341. });
  56342. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56343. get: function () {
  56344. return this._dPadUp;
  56345. },
  56346. set: function (value) {
  56347. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56348. },
  56349. enumerable: true,
  56350. configurable: true
  56351. });
  56352. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56353. get: function () {
  56354. return this._dPadDown;
  56355. },
  56356. set: function (value) {
  56357. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56358. },
  56359. enumerable: true,
  56360. configurable: true
  56361. });
  56362. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56363. get: function () {
  56364. return this._dPadLeft;
  56365. },
  56366. set: function (value) {
  56367. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56368. },
  56369. enumerable: true,
  56370. configurable: true
  56371. });
  56372. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56373. get: function () {
  56374. return this._dPadRight;
  56375. },
  56376. set: function (value) {
  56377. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56378. },
  56379. enumerable: true,
  56380. configurable: true
  56381. });
  56382. Xbox360Pad.prototype.update = function () {
  56383. _super.prototype.update.call(this);
  56384. if (this._isXboxOnePad) {
  56385. this.buttonA = this.browserGamepad.buttons[0].value;
  56386. this.buttonB = this.browserGamepad.buttons[1].value;
  56387. this.buttonX = this.browserGamepad.buttons[2].value;
  56388. this.buttonY = this.browserGamepad.buttons[3].value;
  56389. this.buttonLB = this.browserGamepad.buttons[4].value;
  56390. this.buttonRB = this.browserGamepad.buttons[5].value;
  56391. this.leftTrigger = this.browserGamepad.axes[2];
  56392. this.rightTrigger = this.browserGamepad.axes[5];
  56393. this.buttonBack = this.browserGamepad.buttons[9].value;
  56394. this.buttonStart = this.browserGamepad.buttons[8].value;
  56395. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56396. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56397. this.dPadUp = this.browserGamepad.buttons[11].value;
  56398. this.dPadDown = this.browserGamepad.buttons[12].value;
  56399. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56400. this.dPadRight = this.browserGamepad.buttons[14].value;
  56401. }
  56402. else {
  56403. this.buttonA = this.browserGamepad.buttons[0].value;
  56404. this.buttonB = this.browserGamepad.buttons[1].value;
  56405. this.buttonX = this.browserGamepad.buttons[2].value;
  56406. this.buttonY = this.browserGamepad.buttons[3].value;
  56407. this.buttonLB = this.browserGamepad.buttons[4].value;
  56408. this.buttonRB = this.browserGamepad.buttons[5].value;
  56409. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56410. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56411. this.buttonBack = this.browserGamepad.buttons[8].value;
  56412. this.buttonStart = this.browserGamepad.buttons[9].value;
  56413. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56414. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56415. this.dPadUp = this.browserGamepad.buttons[12].value;
  56416. this.dPadDown = this.browserGamepad.buttons[13].value;
  56417. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56418. this.dPadRight = this.browserGamepad.buttons[15].value;
  56419. }
  56420. };
  56421. return Xbox360Pad;
  56422. }(BABYLON.Gamepad));
  56423. BABYLON.Xbox360Pad = Xbox360Pad;
  56424. })(BABYLON || (BABYLON = {}));
  56425. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56426. var BABYLON;
  56427. (function (BABYLON) {
  56428. var PoseEnabledControllerType;
  56429. (function (PoseEnabledControllerType) {
  56430. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56431. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56432. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56433. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56434. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56435. var PoseEnabledControllerHelper = /** @class */ (function () {
  56436. function PoseEnabledControllerHelper() {
  56437. }
  56438. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56439. // Oculus Touch
  56440. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56441. return new BABYLON.OculusTouchController(vrGamepad);
  56442. }
  56443. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56444. return new BABYLON.WindowsMotionController(vrGamepad);
  56445. }
  56446. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56447. return new BABYLON.ViveController(vrGamepad);
  56448. }
  56449. else {
  56450. return new BABYLON.GenericController(vrGamepad);
  56451. }
  56452. };
  56453. return PoseEnabledControllerHelper;
  56454. }());
  56455. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56456. var PoseEnabledController = /** @class */ (function (_super) {
  56457. __extends(PoseEnabledController, _super);
  56458. function PoseEnabledController(browserGamepad) {
  56459. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56460. _this.deviceScaleFactor = 1;
  56461. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56462. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56463. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56464. _this.position = BABYLON.Vector3.Zero();
  56465. _this.rotationQuaternion = new BABYLON.Quaternion();
  56466. _this.devicePosition = BABYLON.Vector3.Zero();
  56467. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56468. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56469. _this._calculatedRotation = new BABYLON.Quaternion();
  56470. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56471. return _this;
  56472. }
  56473. PoseEnabledController.prototype.update = function () {
  56474. _super.prototype.update.call(this);
  56475. var pose = this.browserGamepad.pose;
  56476. this.updateFromDevice(pose);
  56477. if (this._mesh) {
  56478. this._mesh.position.copyFrom(this._calculatedPosition);
  56479. if (this._mesh.rotationQuaternion) {
  56480. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56481. }
  56482. }
  56483. };
  56484. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56485. if (poseData) {
  56486. this.rawPose = poseData;
  56487. if (poseData.position) {
  56488. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56489. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56490. this.devicePosition.z *= -1;
  56491. }
  56492. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56493. this._calculatedPosition.addInPlace(this.position);
  56494. }
  56495. var pose = this.rawPose;
  56496. if (poseData.orientation && pose.orientation) {
  56497. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56498. if (this._mesh) {
  56499. if (this._mesh.getScene().useRightHandedSystem) {
  56500. this.deviceRotationQuaternion.z *= -1;
  56501. this.deviceRotationQuaternion.w *= -1;
  56502. }
  56503. else {
  56504. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56505. }
  56506. }
  56507. // if the camera is set, rotate to the camera's rotation
  56508. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56509. }
  56510. }
  56511. };
  56512. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56513. if (this._mesh) {
  56514. this._mesh.parent = null;
  56515. }
  56516. this._mesh = mesh;
  56517. if (this._poseControlledCamera) {
  56518. this._mesh.parent = this._poseControlledCamera;
  56519. }
  56520. if (!this._mesh.rotationQuaternion) {
  56521. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56522. }
  56523. };
  56524. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56525. this._poseControlledCamera = camera;
  56526. if (this._mesh) {
  56527. this._mesh.parent = this._poseControlledCamera;
  56528. }
  56529. };
  56530. PoseEnabledController.prototype.dispose = function () {
  56531. if (this._mesh) {
  56532. this._mesh.dispose();
  56533. }
  56534. this._mesh = null;
  56535. _super.prototype.dispose.call(this);
  56536. };
  56537. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56538. get: function () {
  56539. return this._mesh;
  56540. },
  56541. enumerable: true,
  56542. configurable: true
  56543. });
  56544. PoseEnabledController.prototype.getForwardRay = function (length) {
  56545. if (length === void 0) { length = 100; }
  56546. if (!this.mesh) {
  56547. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56548. }
  56549. var m = this.mesh.getWorldMatrix();
  56550. var origin = m.getTranslation();
  56551. var forward = new BABYLON.Vector3(0, 0, -1);
  56552. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56553. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56554. return new BABYLON.Ray(origin, direction, length);
  56555. };
  56556. return PoseEnabledController;
  56557. }(BABYLON.Gamepad));
  56558. BABYLON.PoseEnabledController = PoseEnabledController;
  56559. })(BABYLON || (BABYLON = {}));
  56560. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56561. var BABYLON;
  56562. (function (BABYLON) {
  56563. var WebVRController = /** @class */ (function (_super) {
  56564. __extends(WebVRController, _super);
  56565. function WebVRController(vrGamepad) {
  56566. var _this = _super.call(this, vrGamepad) || this;
  56567. // Observables
  56568. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56569. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56570. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56571. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56572. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56573. _this.pad = { x: 0, y: 0 };
  56574. // avoid GC, store state in a tmp object
  56575. _this._changes = {
  56576. pressChanged: false,
  56577. touchChanged: false,
  56578. valueChanged: false,
  56579. changed: false
  56580. };
  56581. _this._buttons = new Array(vrGamepad.buttons.length);
  56582. _this.hand = vrGamepad.hand;
  56583. return _this;
  56584. }
  56585. WebVRController.prototype.onButtonStateChange = function (callback) {
  56586. this._onButtonStateChange = callback;
  56587. };
  56588. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56589. get: function () {
  56590. return this._defaultModel;
  56591. },
  56592. enumerable: true,
  56593. configurable: true
  56594. });
  56595. WebVRController.prototype.update = function () {
  56596. _super.prototype.update.call(this);
  56597. for (var index = 0; index < this._buttons.length; index++) {
  56598. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56599. }
  56600. ;
  56601. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56602. this.pad.x = this.leftStick.x;
  56603. this.pad.y = this.leftStick.y;
  56604. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56605. }
  56606. };
  56607. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56608. if (!newState) {
  56609. newState = {
  56610. pressed: false,
  56611. touched: false,
  56612. value: 0
  56613. };
  56614. }
  56615. if (!currentState) {
  56616. this._buttons[buttonIndex] = {
  56617. pressed: newState.pressed,
  56618. touched: newState.touched,
  56619. value: newState.value
  56620. };
  56621. return;
  56622. }
  56623. this._checkChanges(newState, currentState);
  56624. if (this._changes.changed) {
  56625. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56626. this.handleButtonChange(buttonIndex, newState, this._changes);
  56627. }
  56628. this._buttons[buttonIndex].pressed = newState.pressed;
  56629. this._buttons[buttonIndex].touched = newState.touched;
  56630. // oculus triggers are never 0, thou not touched.
  56631. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56632. };
  56633. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56634. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56635. this._changes.touchChanged = newState.touched !== currentState.touched;
  56636. this._changes.valueChanged = newState.value !== currentState.value;
  56637. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56638. return this._changes;
  56639. };
  56640. WebVRController.prototype.dispose = function () {
  56641. _super.prototype.dispose.call(this);
  56642. this.onTriggerStateChangedObservable.clear();
  56643. this.onMainButtonStateChangedObservable.clear();
  56644. this.onSecondaryButtonStateChangedObservable.clear();
  56645. this.onPadStateChangedObservable.clear();
  56646. this.onPadValuesChangedObservable.clear();
  56647. };
  56648. return WebVRController;
  56649. }(BABYLON.PoseEnabledController));
  56650. BABYLON.WebVRController = WebVRController;
  56651. })(BABYLON || (BABYLON = {}));
  56652. //# sourceMappingURL=babylon.webVRController.js.map
  56653. var BABYLON;
  56654. (function (BABYLON) {
  56655. var OculusTouchController = /** @class */ (function (_super) {
  56656. __extends(OculusTouchController, _super);
  56657. function OculusTouchController(vrGamepad) {
  56658. var _this = _super.call(this, vrGamepad) || this;
  56659. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56660. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56661. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56662. return _this;
  56663. }
  56664. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56665. var _this = this;
  56666. var meshName;
  56667. // Hand
  56668. if (this.hand === 'left') {
  56669. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56670. }
  56671. else {
  56672. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56673. }
  56674. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56675. /*
  56676. Parent Mesh name: oculus_touch_left
  56677. - body
  56678. - trigger
  56679. - thumbstick
  56680. - grip
  56681. - button_y
  56682. - button_x
  56683. - button_enter
  56684. */
  56685. _this._defaultModel = newMeshes[1];
  56686. _this.attachToMesh(_this._defaultModel);
  56687. if (meshLoaded) {
  56688. meshLoaded(_this._defaultModel);
  56689. }
  56690. });
  56691. };
  56692. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56693. // helper getters for left and right hand.
  56694. get: function () {
  56695. if (this.hand === 'right') {
  56696. return this.onMainButtonStateChangedObservable;
  56697. }
  56698. else {
  56699. throw new Error('No A button on left hand');
  56700. }
  56701. },
  56702. enumerable: true,
  56703. configurable: true
  56704. });
  56705. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56706. get: function () {
  56707. if (this.hand === 'right') {
  56708. return this.onSecondaryButtonStateChangedObservable;
  56709. }
  56710. else {
  56711. throw new Error('No B button on left hand');
  56712. }
  56713. },
  56714. enumerable: true,
  56715. configurable: true
  56716. });
  56717. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56718. get: function () {
  56719. if (this.hand === 'left') {
  56720. return this.onMainButtonStateChangedObservable;
  56721. }
  56722. else {
  56723. throw new Error('No X button on right hand');
  56724. }
  56725. },
  56726. enumerable: true,
  56727. configurable: true
  56728. });
  56729. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56730. get: function () {
  56731. if (this.hand === 'left') {
  56732. return this.onSecondaryButtonStateChangedObservable;
  56733. }
  56734. else {
  56735. throw new Error('No Y button on right hand');
  56736. }
  56737. },
  56738. enumerable: true,
  56739. configurable: true
  56740. });
  56741. /*
  56742. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56743. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56744. 2) secondary trigger (same)
  56745. 3) A (right) X (left), touch, pressed = value
  56746. 4) B / Y
  56747. 5) thumb rest
  56748. */
  56749. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56750. var notifyObject = state; //{ state: state, changes: changes };
  56751. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56752. switch (buttonIdx) {
  56753. case 0:
  56754. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56755. return;
  56756. case 1:// index trigger
  56757. if (this._defaultModel) {
  56758. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56759. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56760. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56761. }
  56762. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56763. return;
  56764. case 2:// secondary trigger
  56765. if (this._defaultModel) {
  56766. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56767. }
  56768. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56769. return;
  56770. case 3:
  56771. if (this._defaultModel) {
  56772. if (notifyObject.pressed) {
  56773. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56774. }
  56775. else {
  56776. (this._defaultModel.getChildren()[1]).position.y = 0;
  56777. }
  56778. }
  56779. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56780. return;
  56781. case 4:
  56782. if (this._defaultModel) {
  56783. if (notifyObject.pressed) {
  56784. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56785. }
  56786. else {
  56787. (this._defaultModel.getChildren()[2]).position.y = 0;
  56788. }
  56789. }
  56790. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56791. return;
  56792. case 5:
  56793. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56794. return;
  56795. }
  56796. };
  56797. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56798. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56799. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56800. return OculusTouchController;
  56801. }(BABYLON.WebVRController));
  56802. BABYLON.OculusTouchController = OculusTouchController;
  56803. })(BABYLON || (BABYLON = {}));
  56804. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56805. var BABYLON;
  56806. (function (BABYLON) {
  56807. var ViveController = /** @class */ (function (_super) {
  56808. __extends(ViveController, _super);
  56809. function ViveController(vrGamepad) {
  56810. var _this = _super.call(this, vrGamepad) || this;
  56811. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56812. return _this;
  56813. }
  56814. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56815. var _this = this;
  56816. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56817. /*
  56818. Parent Mesh name: ViveWand
  56819. - body
  56820. - r_gripper
  56821. - l_gripper
  56822. - menu_button
  56823. - system_button
  56824. - trackpad
  56825. - trigger
  56826. - LED
  56827. */
  56828. _this._defaultModel = newMeshes[1];
  56829. _this.attachToMesh(_this._defaultModel);
  56830. if (meshLoaded) {
  56831. meshLoaded(_this._defaultModel);
  56832. }
  56833. });
  56834. };
  56835. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56836. get: function () {
  56837. return this.onMainButtonStateChangedObservable;
  56838. },
  56839. enumerable: true,
  56840. configurable: true
  56841. });
  56842. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56843. get: function () {
  56844. return this.onMainButtonStateChangedObservable;
  56845. },
  56846. enumerable: true,
  56847. configurable: true
  56848. });
  56849. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56850. get: function () {
  56851. return this.onSecondaryButtonStateChangedObservable;
  56852. },
  56853. enumerable: true,
  56854. configurable: true
  56855. });
  56856. /**
  56857. * Vive mapping:
  56858. * 0: touchpad
  56859. * 1: trigger
  56860. * 2: left AND right buttons
  56861. * 3: menu button
  56862. */
  56863. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56864. var notifyObject = state; //{ state: state, changes: changes };
  56865. switch (buttonIdx) {
  56866. case 0:
  56867. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56868. return;
  56869. case 1:// index trigger
  56870. if (this._defaultModel) {
  56871. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56872. }
  56873. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56874. return;
  56875. case 2:// left AND right button
  56876. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56877. return;
  56878. case 3:
  56879. if (this._defaultModel) {
  56880. if (notifyObject.pressed) {
  56881. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56882. }
  56883. else {
  56884. (this._defaultModel.getChildren()[2]).position.y = 0;
  56885. }
  56886. }
  56887. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56888. return;
  56889. }
  56890. };
  56891. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56892. ViveController.MODEL_FILENAME = 'wand.babylon';
  56893. return ViveController;
  56894. }(BABYLON.WebVRController));
  56895. BABYLON.ViveController = ViveController;
  56896. })(BABYLON || (BABYLON = {}));
  56897. //# sourceMappingURL=babylon.viveController.js.map
  56898. var BABYLON;
  56899. (function (BABYLON) {
  56900. var GenericController = /** @class */ (function (_super) {
  56901. __extends(GenericController, _super);
  56902. function GenericController(vrGamepad) {
  56903. return _super.call(this, vrGamepad) || this;
  56904. }
  56905. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56906. var _this = this;
  56907. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56908. _this._defaultModel = newMeshes[1];
  56909. _this.attachToMesh(_this._defaultModel);
  56910. if (meshLoaded) {
  56911. meshLoaded(_this._defaultModel);
  56912. }
  56913. });
  56914. };
  56915. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56916. console.log("Button id: " + buttonIdx + "state: ");
  56917. console.dir(state);
  56918. };
  56919. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56920. GenericController.MODEL_FILENAME = 'generic.babylon';
  56921. return GenericController;
  56922. }(BABYLON.WebVRController));
  56923. BABYLON.GenericController = GenericController;
  56924. })(BABYLON || (BABYLON = {}));
  56925. //# sourceMappingURL=babylon.genericController.js.map
  56926. var BABYLON;
  56927. (function (BABYLON) {
  56928. var LoadedMeshInfo = /** @class */ (function () {
  56929. function LoadedMeshInfo() {
  56930. this.buttonMeshes = {};
  56931. this.axisMeshes = {};
  56932. }
  56933. return LoadedMeshInfo;
  56934. }());
  56935. var WindowsMotionController = /** @class */ (function (_super) {
  56936. __extends(WindowsMotionController, _super);
  56937. function WindowsMotionController(vrGamepad) {
  56938. var _this = _super.call(this, vrGamepad) || this;
  56939. _this._mapping = {
  56940. // Semantic button names
  56941. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56942. // A mapping of the button name to glTF model node name
  56943. // that should be transformed by button value.
  56944. buttonMeshNames: {
  56945. 'trigger': 'SELECT',
  56946. 'menu': 'MENU',
  56947. 'grip': 'GRASP',
  56948. 'thumbstick': 'THUMBSTICK_PRESS',
  56949. 'trackpad': 'TOUCHPAD_PRESS'
  56950. },
  56951. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56952. buttonObservableNames: {
  56953. 'trigger': 'onTriggerStateChangedObservable',
  56954. 'menu': 'onSecondaryButtonStateChangedObservable',
  56955. 'grip': 'onMainButtonStateChangedObservable',
  56956. 'thumbstick': 'onPadStateChangedObservable',
  56957. 'trackpad': 'onTrackpadChangedObservable'
  56958. },
  56959. // A mapping of the axis name to glTF model node name
  56960. // that should be transformed by axis value.
  56961. // This array mirrors the browserGamepad.axes array, such that
  56962. // the mesh corresponding to axis 0 is in this array index 0.
  56963. axisMeshNames: [
  56964. 'THUMBSTICK_X',
  56965. 'THUMBSTICK_Y',
  56966. 'TOUCHPAD_TOUCH_X',
  56967. 'TOUCHPAD_TOUCH_Y'
  56968. ],
  56969. pointingPoseMeshName: 'POINTING_POSE'
  56970. };
  56971. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56972. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56973. _this._loadedMeshInfo = null;
  56974. return _this;
  56975. }
  56976. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56977. get: function () {
  56978. return this.onTriggerStateChangedObservable;
  56979. },
  56980. enumerable: true,
  56981. configurable: true
  56982. });
  56983. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56984. get: function () {
  56985. return this.onSecondaryButtonStateChangedObservable;
  56986. },
  56987. enumerable: true,
  56988. configurable: true
  56989. });
  56990. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56991. get: function () {
  56992. return this.onMainButtonStateChangedObservable;
  56993. },
  56994. enumerable: true,
  56995. configurable: true
  56996. });
  56997. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56998. get: function () {
  56999. return this.onPadStateChangedObservable;
  57000. },
  57001. enumerable: true,
  57002. configurable: true
  57003. });
  57004. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57005. get: function () {
  57006. return this.onTrackpadChangedObservable;
  57007. },
  57008. enumerable: true,
  57009. configurable: true
  57010. });
  57011. /**
  57012. * Called once per frame by the engine.
  57013. */
  57014. WindowsMotionController.prototype.update = function () {
  57015. _super.prototype.update.call(this);
  57016. // Only need to animate axes if there is a loaded mesh
  57017. if (this._loadedMeshInfo) {
  57018. if (this.browserGamepad.axes) {
  57019. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57020. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57021. }
  57022. }
  57023. }
  57024. };
  57025. /**
  57026. * Called once for each button that changed state since the last frame
  57027. * @param buttonIdx Which button index changed
  57028. * @param state New state of the button
  57029. * @param changes Which properties on the state changed since last frame
  57030. */
  57031. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57032. var buttonName = this._mapping.buttons[buttonIdx];
  57033. if (!buttonName) {
  57034. return;
  57035. }
  57036. // Only emit events for buttons that we know how to map from index to name
  57037. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57038. if (observable) {
  57039. observable.notifyObservers(state);
  57040. }
  57041. this.lerpButtonTransform(buttonName, state.value);
  57042. };
  57043. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57044. // If there is no loaded mesh, there is nothing to transform.
  57045. if (!this._loadedMeshInfo) {
  57046. return;
  57047. }
  57048. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57049. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57050. return;
  57051. }
  57052. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57053. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57054. };
  57055. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57056. if (!this._loadedMeshInfo) {
  57057. return;
  57058. }
  57059. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57060. if (!meshInfo) {
  57061. return;
  57062. }
  57063. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57064. return;
  57065. }
  57066. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57067. var lerpValue = axisValue * 0.5 + 0.5;
  57068. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57069. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57070. };
  57071. /**
  57072. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57073. * @param scene scene in which to add meshes
  57074. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57075. */
  57076. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57077. var _this = this;
  57078. if (forceDefault === void 0) { forceDefault = false; }
  57079. var path;
  57080. var filename;
  57081. // Checking if GLB loader is present
  57082. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  57083. // Determine the device specific folder based on the ID suffix
  57084. var device = 'default';
  57085. if (this.id && !forceDefault) {
  57086. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57087. device = ((match && match[0]) || device);
  57088. }
  57089. // Hand
  57090. if (this.hand === 'left') {
  57091. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57092. }
  57093. else {
  57094. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57095. }
  57096. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57097. }
  57098. else {
  57099. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57100. path = BABYLON.GenericController.MODEL_BASE_URL;
  57101. filename = BABYLON.GenericController.MODEL_FILENAME;
  57102. }
  57103. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57104. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57105. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57106. if (!_this._loadedMeshInfo) {
  57107. return;
  57108. }
  57109. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57110. _this.attachToMesh(_this._defaultModel);
  57111. if (meshLoaded) {
  57112. meshLoaded(_this._defaultModel);
  57113. }
  57114. }, null, function (scene, message) {
  57115. BABYLON.Tools.Log(message);
  57116. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57117. if (!forceDefault) {
  57118. _this.initControllerMesh(scene, meshLoaded, true);
  57119. }
  57120. });
  57121. };
  57122. /**
  57123. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57124. * can be transformed by button presses and axes values, based on this._mapping.
  57125. *
  57126. * @param scene scene in which the meshes exist
  57127. * @param meshes list of meshes that make up the controller model to process
  57128. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57129. */
  57130. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57131. var loadedMeshInfo = null;
  57132. // Create a new mesh to contain the glTF hierarchy
  57133. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57134. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57135. var childMesh = null;
  57136. for (var i = 0; i < meshes.length; i++) {
  57137. var mesh = meshes[i];
  57138. if (!mesh.parent) {
  57139. // Exclude controller meshes from picking results
  57140. mesh.isPickable = false;
  57141. // Handle root node, attach to the new parentMesh
  57142. childMesh = mesh;
  57143. break;
  57144. }
  57145. }
  57146. if (childMesh) {
  57147. childMesh.setParent(parentMesh);
  57148. // Create our mesh info. Note that this method will always return non-null.
  57149. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57150. }
  57151. else {
  57152. BABYLON.Tools.Warn('Could not find root node in model file.');
  57153. }
  57154. return loadedMeshInfo;
  57155. };
  57156. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57157. var loadedMeshInfo = new LoadedMeshInfo();
  57158. var i;
  57159. loadedMeshInfo.rootNode = rootNode;
  57160. // Reset the caches
  57161. loadedMeshInfo.buttonMeshes = {};
  57162. loadedMeshInfo.axisMeshes = {};
  57163. // Button Meshes
  57164. for (i = 0; i < this._mapping.buttons.length; i++) {
  57165. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57166. if (!buttonMeshName) {
  57167. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57168. continue;
  57169. }
  57170. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57171. if (!buttonMesh) {
  57172. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57173. continue;
  57174. }
  57175. var buttonMeshInfo = {
  57176. index: i,
  57177. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57178. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57179. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57180. };
  57181. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57182. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57183. }
  57184. else {
  57185. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57186. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57187. '(VALUE: ' + !!buttonMeshInfo.value +
  57188. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57189. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57190. ')');
  57191. }
  57192. }
  57193. // Axis Meshes
  57194. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57195. var axisMeshName = this._mapping.axisMeshNames[i];
  57196. if (!axisMeshName) {
  57197. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57198. continue;
  57199. }
  57200. var axisMesh = getChildByName(rootNode, axisMeshName);
  57201. if (!axisMesh) {
  57202. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57203. continue;
  57204. }
  57205. var axisMeshInfo = {
  57206. index: i,
  57207. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57208. min: getImmediateChildByName(axisMesh, 'MIN'),
  57209. max: getImmediateChildByName(axisMesh, 'MAX')
  57210. };
  57211. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57212. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57213. }
  57214. else {
  57215. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57216. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57217. '(VALUE: ' + !!axisMeshInfo.value +
  57218. ', MIN: ' + !!axisMeshInfo.min +
  57219. ', MAX:' + !!axisMeshInfo.max +
  57220. ')');
  57221. }
  57222. }
  57223. // Pointing Ray
  57224. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57225. if (!loadedMeshInfo.pointingPoseNode) {
  57226. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57227. }
  57228. return loadedMeshInfo;
  57229. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57230. function getChildByName(node, name) {
  57231. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57232. }
  57233. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57234. function getImmediateChildByName(node, name) {
  57235. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57236. }
  57237. };
  57238. WindowsMotionController.prototype.getForwardRay = function (length) {
  57239. if (length === void 0) { length = 100; }
  57240. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57241. return _super.prototype.getForwardRay.call(this, length);
  57242. }
  57243. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57244. var origin = m.getTranslation();
  57245. var forward = new BABYLON.Vector3(0, 0, -1);
  57246. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57247. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57248. return new BABYLON.Ray(origin, direction, length);
  57249. };
  57250. WindowsMotionController.prototype.dispose = function () {
  57251. _super.prototype.dispose.call(this);
  57252. this.onTrackpadChangedObservable.clear();
  57253. };
  57254. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57255. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57256. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57257. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57258. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57259. return WindowsMotionController;
  57260. }(BABYLON.WebVRController));
  57261. BABYLON.WindowsMotionController = WindowsMotionController;
  57262. })(BABYLON || (BABYLON = {}));
  57263. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57264. var BABYLON;
  57265. (function (BABYLON) {
  57266. var FollowCamera = /** @class */ (function (_super) {
  57267. __extends(FollowCamera, _super);
  57268. function FollowCamera(name, position, scene, lockedTarget) {
  57269. if (lockedTarget === void 0) { lockedTarget = null; }
  57270. var _this = _super.call(this, name, position, scene) || this;
  57271. _this.radius = 12;
  57272. _this.rotationOffset = 0;
  57273. _this.heightOffset = 4;
  57274. _this.cameraAcceleration = 0.05;
  57275. _this.maxCameraSpeed = 20;
  57276. _this.lockedTarget = lockedTarget;
  57277. return _this;
  57278. }
  57279. FollowCamera.prototype.getRadians = function (degrees) {
  57280. return degrees * Math.PI / 180;
  57281. };
  57282. FollowCamera.prototype.follow = function (cameraTarget) {
  57283. if (!cameraTarget)
  57284. return;
  57285. var yRotation;
  57286. if (cameraTarget.rotationQuaternion) {
  57287. var rotMatrix = new BABYLON.Matrix();
  57288. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57289. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57290. }
  57291. else {
  57292. yRotation = cameraTarget.rotation.y;
  57293. }
  57294. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57295. var targetPosition = cameraTarget.getAbsolutePosition();
  57296. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57297. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57298. var dx = targetX - this.position.x;
  57299. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57300. var dz = (targetZ) - this.position.z;
  57301. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57302. var vy = dy * this.cameraAcceleration;
  57303. var vz = dz * this.cameraAcceleration * 2;
  57304. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57305. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57306. }
  57307. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57308. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57309. }
  57310. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57311. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57312. }
  57313. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57314. this.setTarget(targetPosition);
  57315. };
  57316. FollowCamera.prototype._checkInputs = function () {
  57317. _super.prototype._checkInputs.call(this);
  57318. if (this.lockedTarget) {
  57319. this.follow(this.lockedTarget);
  57320. }
  57321. };
  57322. FollowCamera.prototype.getClassName = function () {
  57323. return "FollowCamera";
  57324. };
  57325. __decorate([
  57326. BABYLON.serialize()
  57327. ], FollowCamera.prototype, "radius", void 0);
  57328. __decorate([
  57329. BABYLON.serialize()
  57330. ], FollowCamera.prototype, "rotationOffset", void 0);
  57331. __decorate([
  57332. BABYLON.serialize()
  57333. ], FollowCamera.prototype, "heightOffset", void 0);
  57334. __decorate([
  57335. BABYLON.serialize()
  57336. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57337. __decorate([
  57338. BABYLON.serialize()
  57339. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57340. __decorate([
  57341. BABYLON.serializeAsMeshReference("lockedTargetId")
  57342. ], FollowCamera.prototype, "lockedTarget", void 0);
  57343. return FollowCamera;
  57344. }(BABYLON.TargetCamera));
  57345. BABYLON.FollowCamera = FollowCamera;
  57346. var ArcFollowCamera = /** @class */ (function (_super) {
  57347. __extends(ArcFollowCamera, _super);
  57348. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57349. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57350. _this.alpha = alpha;
  57351. _this.beta = beta;
  57352. _this.radius = radius;
  57353. _this.target = target;
  57354. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57355. _this.follow();
  57356. return _this;
  57357. }
  57358. ArcFollowCamera.prototype.follow = function () {
  57359. if (!this.target) {
  57360. return;
  57361. }
  57362. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57363. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57364. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57365. var targetPosition = this.target.getAbsolutePosition();
  57366. this.position = targetPosition.add(this._cartesianCoordinates);
  57367. this.setTarget(targetPosition);
  57368. };
  57369. ArcFollowCamera.prototype._checkInputs = function () {
  57370. _super.prototype._checkInputs.call(this);
  57371. this.follow();
  57372. };
  57373. ArcFollowCamera.prototype.getClassName = function () {
  57374. return "ArcFollowCamera";
  57375. };
  57376. return ArcFollowCamera;
  57377. }(BABYLON.TargetCamera));
  57378. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57379. })(BABYLON || (BABYLON = {}));
  57380. //# sourceMappingURL=babylon.followCamera.js.map
  57381. var BABYLON;
  57382. (function (BABYLON) {
  57383. // We're mainly based on the logic defined into the FreeCamera code
  57384. var UniversalCamera = /** @class */ (function (_super) {
  57385. __extends(UniversalCamera, _super);
  57386. //-- end properties for backward compatibility for inputs
  57387. function UniversalCamera(name, position, scene) {
  57388. var _this = _super.call(this, name, position, scene) || this;
  57389. _this.inputs.addGamepad();
  57390. return _this;
  57391. }
  57392. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57393. //-- Begin properties for backward compatibility for inputs
  57394. get: function () {
  57395. var gamepad = this.inputs.attached["gamepad"];
  57396. if (gamepad)
  57397. return gamepad.gamepadAngularSensibility;
  57398. return 0;
  57399. },
  57400. set: function (value) {
  57401. var gamepad = this.inputs.attached["gamepad"];
  57402. if (gamepad)
  57403. gamepad.gamepadAngularSensibility = value;
  57404. },
  57405. enumerable: true,
  57406. configurable: true
  57407. });
  57408. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57409. get: function () {
  57410. var gamepad = this.inputs.attached["gamepad"];
  57411. if (gamepad)
  57412. return gamepad.gamepadMoveSensibility;
  57413. return 0;
  57414. },
  57415. set: function (value) {
  57416. var gamepad = this.inputs.attached["gamepad"];
  57417. if (gamepad)
  57418. gamepad.gamepadMoveSensibility = value;
  57419. },
  57420. enumerable: true,
  57421. configurable: true
  57422. });
  57423. UniversalCamera.prototype.getClassName = function () {
  57424. return "UniversalCamera";
  57425. };
  57426. return UniversalCamera;
  57427. }(BABYLON.TouchCamera));
  57428. BABYLON.UniversalCamera = UniversalCamera;
  57429. })(BABYLON || (BABYLON = {}));
  57430. //# sourceMappingURL=babylon.universalCamera.js.map
  57431. var BABYLON;
  57432. (function (BABYLON) {
  57433. // We're mainly based on the logic defined into the FreeCamera code
  57434. var GamepadCamera = /** @class */ (function (_super) {
  57435. __extends(GamepadCamera, _super);
  57436. //-- end properties for backward compatibility for inputs
  57437. function GamepadCamera(name, position, scene) {
  57438. return _super.call(this, name, position, scene) || this;
  57439. }
  57440. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57441. //-- Begin properties for backward compatibility for inputs
  57442. get: function () {
  57443. var gamepad = this.inputs.attached["gamepad"];
  57444. if (gamepad)
  57445. return gamepad.gamepadAngularSensibility;
  57446. return 0;
  57447. },
  57448. set: function (value) {
  57449. var gamepad = this.inputs.attached["gamepad"];
  57450. if (gamepad)
  57451. gamepad.gamepadAngularSensibility = value;
  57452. },
  57453. enumerable: true,
  57454. configurable: true
  57455. });
  57456. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57457. get: function () {
  57458. var gamepad = this.inputs.attached["gamepad"];
  57459. if (gamepad)
  57460. return gamepad.gamepadMoveSensibility;
  57461. return 0;
  57462. },
  57463. set: function (value) {
  57464. var gamepad = this.inputs.attached["gamepad"];
  57465. if (gamepad)
  57466. gamepad.gamepadMoveSensibility = value;
  57467. },
  57468. enumerable: true,
  57469. configurable: true
  57470. });
  57471. GamepadCamera.prototype.getClassName = function () {
  57472. return "GamepadCamera";
  57473. };
  57474. return GamepadCamera;
  57475. }(BABYLON.UniversalCamera));
  57476. BABYLON.GamepadCamera = GamepadCamera;
  57477. })(BABYLON || (BABYLON = {}));
  57478. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57479. var BABYLON;
  57480. (function (BABYLON) {
  57481. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57482. function PostProcessRenderPipelineManager() {
  57483. this._renderPipelines = {};
  57484. }
  57485. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57486. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57487. };
  57488. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57489. if (unique === void 0) { unique = false; }
  57490. var renderPipeline = this._renderPipelines[renderPipelineName];
  57491. if (!renderPipeline) {
  57492. return;
  57493. }
  57494. renderPipeline._attachCameras(cameras, unique);
  57495. };
  57496. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57497. var renderPipeline = this._renderPipelines[renderPipelineName];
  57498. if (!renderPipeline) {
  57499. return;
  57500. }
  57501. renderPipeline._detachCameras(cameras);
  57502. };
  57503. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57504. var renderPipeline = this._renderPipelines[renderPipelineName];
  57505. if (!renderPipeline) {
  57506. return;
  57507. }
  57508. renderPipeline._enableEffect(renderEffectName, cameras);
  57509. };
  57510. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57511. var renderPipeline = this._renderPipelines[renderPipelineName];
  57512. if (!renderPipeline) {
  57513. return;
  57514. }
  57515. renderPipeline._disableEffect(renderEffectName, cameras);
  57516. };
  57517. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57518. var renderPipeline = this._renderPipelines[renderPipelineName];
  57519. if (!renderPipeline) {
  57520. return;
  57521. }
  57522. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57523. };
  57524. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57525. var renderPipeline = this._renderPipelines[renderPipelineName];
  57526. if (!renderPipeline) {
  57527. return;
  57528. }
  57529. renderPipeline._disableDisplayOnlyPass(cameras);
  57530. };
  57531. PostProcessRenderPipelineManager.prototype.update = function () {
  57532. for (var renderPipelineName in this._renderPipelines) {
  57533. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57534. var pipeline = this._renderPipelines[renderPipelineName];
  57535. if (!pipeline.isSupported) {
  57536. pipeline.dispose();
  57537. delete this._renderPipelines[renderPipelineName];
  57538. }
  57539. else {
  57540. pipeline._update();
  57541. }
  57542. }
  57543. }
  57544. };
  57545. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57546. for (var renderPipelineName in this._renderPipelines) {
  57547. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57548. var pipeline = this._renderPipelines[renderPipelineName];
  57549. pipeline._rebuild();
  57550. }
  57551. }
  57552. };
  57553. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57554. for (var renderPipelineName in this._renderPipelines) {
  57555. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57556. var pipeline = this._renderPipelines[renderPipelineName];
  57557. pipeline.dispose();
  57558. }
  57559. }
  57560. };
  57561. return PostProcessRenderPipelineManager;
  57562. }());
  57563. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57564. })(BABYLON || (BABYLON = {}));
  57565. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57566. var BABYLON;
  57567. (function (BABYLON) {
  57568. var PostProcessRenderPass = /** @class */ (function () {
  57569. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57570. this._refCount = 0;
  57571. this._name = name;
  57572. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57573. this.setRenderList(renderList);
  57574. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57575. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57576. this._scene = scene;
  57577. this._renderList = renderList;
  57578. }
  57579. // private
  57580. PostProcessRenderPass.prototype._incRefCount = function () {
  57581. if (this._refCount === 0) {
  57582. this._scene.customRenderTargets.push(this._renderTexture);
  57583. }
  57584. return ++this._refCount;
  57585. };
  57586. PostProcessRenderPass.prototype._decRefCount = function () {
  57587. this._refCount--;
  57588. if (this._refCount <= 0) {
  57589. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57590. }
  57591. return this._refCount;
  57592. };
  57593. PostProcessRenderPass.prototype._update = function () {
  57594. this.setRenderList(this._renderList);
  57595. };
  57596. // public
  57597. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57598. this._renderTexture.renderList = renderList;
  57599. };
  57600. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57601. return this._renderTexture;
  57602. };
  57603. return PostProcessRenderPass;
  57604. }());
  57605. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57606. })(BABYLON || (BABYLON = {}));
  57607. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57608. var BABYLON;
  57609. (function (BABYLON) {
  57610. var PostProcessRenderEffect = /** @class */ (function () {
  57611. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57612. this._name = name;
  57613. this._singleInstance = singleInstance || true;
  57614. this._getPostProcess = getPostProcess;
  57615. this._cameras = {};
  57616. this._indicesForCamera = {};
  57617. this._postProcesses = {};
  57618. this._renderPasses = {};
  57619. this._renderEffectAsPasses = {};
  57620. }
  57621. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57622. get: function () {
  57623. for (var index in this._postProcesses) {
  57624. if (!this._postProcesses[index].isSupported) {
  57625. return false;
  57626. }
  57627. }
  57628. return true;
  57629. },
  57630. enumerable: true,
  57631. configurable: true
  57632. });
  57633. PostProcessRenderEffect.prototype._update = function () {
  57634. for (var renderPassName in this._renderPasses) {
  57635. this._renderPasses[renderPassName]._update();
  57636. }
  57637. };
  57638. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57639. this._renderPasses[renderPass._name] = renderPass;
  57640. this._linkParameters();
  57641. };
  57642. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57643. delete this._renderPasses[renderPass._name];
  57644. this._linkParameters();
  57645. };
  57646. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57647. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57648. this._linkParameters();
  57649. };
  57650. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57651. for (var renderPassName in this._renderPasses) {
  57652. if (renderPassName === passName) {
  57653. return this._renderPasses[passName];
  57654. }
  57655. }
  57656. return null;
  57657. };
  57658. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57659. this._renderPasses = {};
  57660. this._linkParameters();
  57661. };
  57662. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57663. var cameraKey;
  57664. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57665. if (!cams) {
  57666. return;
  57667. }
  57668. for (var i = 0; i < cams.length; i++) {
  57669. var camera = cams[i];
  57670. var cameraName = camera.name;
  57671. if (this._singleInstance) {
  57672. cameraKey = 0;
  57673. }
  57674. else {
  57675. cameraKey = cameraName;
  57676. }
  57677. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57678. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57679. if (!this._indicesForCamera[cameraName]) {
  57680. this._indicesForCamera[cameraName] = [];
  57681. }
  57682. this._indicesForCamera[cameraName].push(index);
  57683. if (!this._cameras[cameraName]) {
  57684. this._cameras[cameraName] = camera;
  57685. }
  57686. for (var passName in this._renderPasses) {
  57687. this._renderPasses[passName]._incRefCount();
  57688. }
  57689. }
  57690. this._linkParameters();
  57691. };
  57692. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57693. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57694. if (!cams) {
  57695. return;
  57696. }
  57697. for (var i = 0; i < cams.length; i++) {
  57698. var camera = cams[i];
  57699. var cameraName = camera.name;
  57700. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57701. if (this._cameras[cameraName]) {
  57702. //this._indicesForCamera.splice(index, 1);
  57703. this._cameras[cameraName] = null;
  57704. }
  57705. for (var passName in this._renderPasses) {
  57706. this._renderPasses[passName]._decRefCount();
  57707. }
  57708. }
  57709. };
  57710. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57711. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57712. if (!cams) {
  57713. return;
  57714. }
  57715. for (var i = 0; i < cams.length; i++) {
  57716. var camera = cams[i];
  57717. var cameraName = camera.name;
  57718. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57719. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57720. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57721. }
  57722. }
  57723. for (var passName in this._renderPasses) {
  57724. this._renderPasses[passName]._incRefCount();
  57725. }
  57726. }
  57727. };
  57728. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57729. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57730. if (!cams) {
  57731. return;
  57732. }
  57733. for (var i = 0; i < cams.length; i++) {
  57734. var camera = cams[i];
  57735. var cameraName = camera.Name;
  57736. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57737. for (var passName in this._renderPasses) {
  57738. this._renderPasses[passName]._decRefCount();
  57739. }
  57740. }
  57741. };
  57742. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57743. if (this._singleInstance) {
  57744. return this._postProcesses[0];
  57745. }
  57746. else {
  57747. if (!camera) {
  57748. return null;
  57749. }
  57750. return this._postProcesses[camera.name];
  57751. }
  57752. };
  57753. PostProcessRenderEffect.prototype._linkParameters = function () {
  57754. var _this = this;
  57755. for (var index in this._postProcesses) {
  57756. if (this.applyParameters) {
  57757. this.applyParameters(this._postProcesses[index]);
  57758. }
  57759. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57760. _this._linkTextures(effect);
  57761. });
  57762. }
  57763. };
  57764. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57765. for (var renderPassName in this._renderPasses) {
  57766. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57767. }
  57768. for (var renderEffectName in this._renderEffectAsPasses) {
  57769. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57770. }
  57771. };
  57772. return PostProcessRenderEffect;
  57773. }());
  57774. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57775. })(BABYLON || (BABYLON = {}));
  57776. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57777. var BABYLON;
  57778. (function (BABYLON) {
  57779. var PostProcessRenderPipeline = /** @class */ (function () {
  57780. function PostProcessRenderPipeline(engine, name) {
  57781. this._engine = engine;
  57782. this._name = name;
  57783. this._renderEffects = {};
  57784. this._renderEffectsForIsolatedPass = new Array();
  57785. this._cameras = [];
  57786. }
  57787. PostProcessRenderPipeline.prototype.getClassName = function () {
  57788. return "PostProcessRenderPipeline";
  57789. };
  57790. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57791. get: function () {
  57792. for (var renderEffectName in this._renderEffects) {
  57793. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57794. if (!this._renderEffects[renderEffectName].isSupported) {
  57795. return false;
  57796. }
  57797. }
  57798. }
  57799. return true;
  57800. },
  57801. enumerable: true,
  57802. configurable: true
  57803. });
  57804. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57805. this._renderEffects[renderEffect._name] = renderEffect;
  57806. };
  57807. // private
  57808. PostProcessRenderPipeline.prototype._rebuild = function () {
  57809. };
  57810. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57811. var renderEffects = this._renderEffects[renderEffectName];
  57812. if (!renderEffects) {
  57813. return;
  57814. }
  57815. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57816. };
  57817. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57818. var renderEffects = this._renderEffects[renderEffectName];
  57819. if (!renderEffects) {
  57820. return;
  57821. }
  57822. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57823. };
  57824. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57825. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57826. if (!cams) {
  57827. return;
  57828. }
  57829. var indicesToDelete = [];
  57830. var i;
  57831. for (i = 0; i < cams.length; i++) {
  57832. var camera = cams[i];
  57833. var cameraName = camera.name;
  57834. if (this._cameras.indexOf(camera) === -1) {
  57835. this._cameras[cameraName] = camera;
  57836. }
  57837. else if (unique) {
  57838. indicesToDelete.push(i);
  57839. }
  57840. }
  57841. for (i = 0; i < indicesToDelete.length; i++) {
  57842. cameras.splice(indicesToDelete[i], 1);
  57843. }
  57844. for (var renderEffectName in this._renderEffects) {
  57845. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57846. this._renderEffects[renderEffectName]._attachCameras(cams);
  57847. }
  57848. }
  57849. };
  57850. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57851. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57852. if (!cams) {
  57853. return;
  57854. }
  57855. for (var renderEffectName in this._renderEffects) {
  57856. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57857. this._renderEffects[renderEffectName]._detachCameras(cams);
  57858. }
  57859. }
  57860. for (var i = 0; i < cams.length; i++) {
  57861. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57862. }
  57863. };
  57864. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57865. var _this = this;
  57866. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57867. if (!cams) {
  57868. return;
  57869. }
  57870. var pass = null;
  57871. var renderEffectName;
  57872. for (renderEffectName in this._renderEffects) {
  57873. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57874. pass = this._renderEffects[renderEffectName].getPass(passName);
  57875. if (pass != null) {
  57876. break;
  57877. }
  57878. }
  57879. }
  57880. if (pass === null) {
  57881. return;
  57882. }
  57883. for (renderEffectName in this._renderEffects) {
  57884. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57885. this._renderEffects[renderEffectName]._disable(cams);
  57886. }
  57887. }
  57888. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57889. for (var i = 0; i < cams.length; i++) {
  57890. var camera = cams[i];
  57891. var cameraName = camera.name;
  57892. 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); });
  57893. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57894. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57895. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57896. }
  57897. };
  57898. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57899. var _this = this;
  57900. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57901. if (!cams) {
  57902. return;
  57903. }
  57904. for (var i = 0; i < cams.length; i++) {
  57905. var camera = cams[i];
  57906. var cameraName = camera.name;
  57907. 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); });
  57908. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57909. }
  57910. for (var renderEffectName in this._renderEffects) {
  57911. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57912. this._renderEffects[renderEffectName]._enable(cams);
  57913. }
  57914. }
  57915. };
  57916. PostProcessRenderPipeline.prototype._update = function () {
  57917. for (var renderEffectName in this._renderEffects) {
  57918. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57919. this._renderEffects[renderEffectName]._update();
  57920. }
  57921. }
  57922. for (var i = 0; i < this._cameras.length; i++) {
  57923. var cameraName = this._cameras[i].name;
  57924. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57925. this._renderEffectsForIsolatedPass[cameraName]._update();
  57926. }
  57927. }
  57928. };
  57929. PostProcessRenderPipeline.prototype._reset = function () {
  57930. this._renderEffects = {};
  57931. this._renderEffectsForIsolatedPass = new Array();
  57932. };
  57933. PostProcessRenderPipeline.prototype.dispose = function () {
  57934. // Must be implemented by children
  57935. };
  57936. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57937. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57938. __decorate([
  57939. BABYLON.serialize()
  57940. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57941. return PostProcessRenderPipeline;
  57942. }());
  57943. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57944. })(BABYLON || (BABYLON = {}));
  57945. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57946. var BABYLON;
  57947. (function (BABYLON) {
  57948. var DepthRenderer = /** @class */ (function () {
  57949. function DepthRenderer(scene, type) {
  57950. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57951. var _this = this;
  57952. this._scene = scene;
  57953. var engine = scene.getEngine();
  57954. // Render target
  57955. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57956. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57957. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57958. this._depthMap.refreshRate = 1;
  57959. this._depthMap.renderParticles = false;
  57960. this._depthMap.renderList = null;
  57961. // set default depth value to 1.0 (far away)
  57962. this._depthMap.onClearObservable.add(function (engine) {
  57963. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57964. });
  57965. // Custom render function
  57966. var renderSubMesh = function (subMesh) {
  57967. var mesh = subMesh.getRenderingMesh();
  57968. var scene = _this._scene;
  57969. var engine = scene.getEngine();
  57970. var material = subMesh.getMaterial();
  57971. if (!material) {
  57972. return;
  57973. }
  57974. // Culling and reverse (right handed system)
  57975. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  57976. // Managing instances
  57977. var batch = mesh._getInstancesRenderList(subMesh._id);
  57978. if (batch.mustReturn) {
  57979. return;
  57980. }
  57981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57982. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57983. engine.enableEffect(_this._effect);
  57984. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57985. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57986. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57987. // Alpha test
  57988. if (material && material.needAlphaTesting()) {
  57989. var alphaTexture = material.getAlphaTestTexture();
  57990. if (alphaTexture) {
  57991. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57992. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57993. }
  57994. }
  57995. // Bones
  57996. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57997. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57998. }
  57999. // Draw
  58000. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58001. }
  58002. };
  58003. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58004. var index;
  58005. if (depthOnlySubMeshes.length) {
  58006. engine.setColorWrite(false);
  58007. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58008. renderSubMesh(depthOnlySubMeshes.data[index]);
  58009. }
  58010. engine.setColorWrite(true);
  58011. }
  58012. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58013. renderSubMesh(opaqueSubMeshes.data[index]);
  58014. }
  58015. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58016. renderSubMesh(alphaTestSubMeshes.data[index]);
  58017. }
  58018. };
  58019. }
  58020. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58021. var material = subMesh.getMaterial();
  58022. if (material.disableDepthWrite) {
  58023. return false;
  58024. }
  58025. var defines = [];
  58026. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58027. var mesh = subMesh.getMesh();
  58028. // Alpha test
  58029. if (material && material.needAlphaTesting()) {
  58030. defines.push("#define ALPHATEST");
  58031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58032. attribs.push(BABYLON.VertexBuffer.UVKind);
  58033. defines.push("#define UV1");
  58034. }
  58035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58037. defines.push("#define UV2");
  58038. }
  58039. }
  58040. // Bones
  58041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58044. if (mesh.numBoneInfluencers > 4) {
  58045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58047. }
  58048. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58049. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58050. }
  58051. else {
  58052. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58053. }
  58054. // Instances
  58055. if (useInstances) {
  58056. defines.push("#define INSTANCES");
  58057. attribs.push("world0");
  58058. attribs.push("world1");
  58059. attribs.push("world2");
  58060. attribs.push("world3");
  58061. }
  58062. // Get correct effect
  58063. var join = defines.join("\n");
  58064. if (this._cachedDefines !== join) {
  58065. this._cachedDefines = join;
  58066. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58067. }
  58068. return this._effect.isReady();
  58069. };
  58070. DepthRenderer.prototype.getDepthMap = function () {
  58071. return this._depthMap;
  58072. };
  58073. // Methods
  58074. DepthRenderer.prototype.dispose = function () {
  58075. this._depthMap.dispose();
  58076. };
  58077. return DepthRenderer;
  58078. }());
  58079. BABYLON.DepthRenderer = DepthRenderer;
  58080. })(BABYLON || (BABYLON = {}));
  58081. //# sourceMappingURL=babylon.depthRenderer.js.map
  58082. var BABYLON;
  58083. (function (BABYLON) {
  58084. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58085. __extends(SSAORenderingPipeline, _super);
  58086. /**
  58087. * @constructor
  58088. * @param {string} name - The rendering pipeline name
  58089. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58090. * @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 }
  58091. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58092. */
  58093. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58094. var _this = _super.call(this, scene.getEngine(), name) || this;
  58095. // Members
  58096. /**
  58097. * The PassPostProcess id in the pipeline that contains the original scene color
  58098. * @type {string}
  58099. */
  58100. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58101. /**
  58102. * The SSAO PostProcess id in the pipeline
  58103. * @type {string}
  58104. */
  58105. _this.SSAORenderEffect = "SSAORenderEffect";
  58106. /**
  58107. * The horizontal blur PostProcess id in the pipeline
  58108. * @type {string}
  58109. */
  58110. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58111. /**
  58112. * The vertical blur PostProcess id in the pipeline
  58113. * @type {string}
  58114. */
  58115. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58116. /**
  58117. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58118. * @type {string}
  58119. */
  58120. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58121. /**
  58122. * The output strength of the SSAO post-process. Default value is 1.0.
  58123. * @type {number}
  58124. */
  58125. _this.totalStrength = 1.0;
  58126. /**
  58127. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58128. * @type {number}
  58129. */
  58130. _this.radius = 0.0001;
  58131. /**
  58132. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58133. * Must not be equal to fallOff and superior to fallOff.
  58134. * Default value is 0.975
  58135. * @type {number}
  58136. */
  58137. _this.area = 0.0075;
  58138. /**
  58139. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58140. * Must not be equal to area and inferior to area.
  58141. * Default value is 0.0
  58142. * @type {number}
  58143. */
  58144. _this.fallOff = 0.000001;
  58145. /**
  58146. * The base color of the SSAO post-process
  58147. * The final result is "base + ssao" between [0, 1]
  58148. * @type {number}
  58149. */
  58150. _this.base = 0.5;
  58151. _this._firstUpdate = true;
  58152. _this._scene = scene;
  58153. // Set up assets
  58154. _this._createRandomTexture();
  58155. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58156. var ssaoRatio = ratio.ssaoRatio || ratio;
  58157. var combineRatio = ratio.combineRatio || ratio;
  58158. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58159. _this._createSSAOPostProcess(ssaoRatio);
  58160. _this._createBlurPostProcess(ssaoRatio);
  58161. _this._createSSAOCombinePostProcess(combineRatio);
  58162. // Set up pipeline
  58163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58164. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58165. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58166. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58167. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58168. // Finish
  58169. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58170. if (cameras)
  58171. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58172. return _this;
  58173. }
  58174. // Public Methods
  58175. /**
  58176. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58177. */
  58178. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58179. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58180. for (var i = 0; i < this._scene.cameras.length; i++) {
  58181. var camera = this._scene.cameras[i];
  58182. this._originalColorPostProcess.dispose(camera);
  58183. this._ssaoPostProcess.dispose(camera);
  58184. this._blurHPostProcess.dispose(camera);
  58185. this._blurVPostProcess.dispose(camera);
  58186. this._ssaoCombinePostProcess.dispose(camera);
  58187. }
  58188. this._randomTexture.dispose();
  58189. if (disableDepthRender)
  58190. this._scene.disableDepthRenderer();
  58191. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58192. _super.prototype.dispose.call(this);
  58193. };
  58194. // Private Methods
  58195. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58196. var _this = this;
  58197. var size = 16;
  58198. 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);
  58199. 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);
  58200. this._blurHPostProcess.onActivateObservable.add(function () {
  58201. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58202. _this._blurHPostProcess.kernel = size * dw;
  58203. });
  58204. this._blurVPostProcess.onActivateObservable.add(function () {
  58205. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58206. _this._blurVPostProcess.kernel = size * dw;
  58207. });
  58208. };
  58209. SSAORenderingPipeline.prototype._rebuild = function () {
  58210. this._firstUpdate = true;
  58211. _super.prototype._rebuild.call(this);
  58212. };
  58213. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58214. var _this = this;
  58215. var numSamples = 16;
  58216. var sampleSphere = [
  58217. 0.5381, 0.1856, -0.4319,
  58218. 0.1379, 0.2486, 0.4430,
  58219. 0.3371, 0.5679, -0.0057,
  58220. -0.6999, -0.0451, -0.0019,
  58221. 0.0689, -0.1598, -0.8547,
  58222. 0.0560, 0.0069, -0.1843,
  58223. -0.0146, 0.1402, 0.0762,
  58224. 0.0100, -0.1924, -0.0344,
  58225. -0.3577, -0.5301, -0.4358,
  58226. -0.3169, 0.1063, 0.0158,
  58227. 0.0103, -0.5869, 0.0046,
  58228. -0.0897, -0.4940, 0.3287,
  58229. 0.7119, -0.0154, -0.0918,
  58230. -0.0533, 0.0596, -0.5411,
  58231. 0.0352, -0.0631, 0.5460,
  58232. -0.4776, 0.2847, -0.0271
  58233. ];
  58234. var samplesFactor = 1.0 / numSamples;
  58235. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58236. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58237. "area", "fallOff", "base", "range", "viewport"
  58238. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58239. this._ssaoPostProcess.onApply = function (effect) {
  58240. if (_this._firstUpdate) {
  58241. effect.setArray3("sampleSphere", sampleSphere);
  58242. effect.setFloat("samplesFactor", samplesFactor);
  58243. effect.setFloat("randTextureTiles", 4.0);
  58244. }
  58245. effect.setFloat("totalStrength", _this.totalStrength);
  58246. effect.setFloat("radius", _this.radius);
  58247. effect.setFloat("area", _this.area);
  58248. effect.setFloat("fallOff", _this.fallOff);
  58249. effect.setFloat("base", _this.base);
  58250. effect.setTexture("textureSampler", _this._depthTexture);
  58251. effect.setTexture("randomSampler", _this._randomTexture);
  58252. };
  58253. };
  58254. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58255. var _this = this;
  58256. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58257. this._ssaoCombinePostProcess.onApply = function (effect) {
  58258. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58259. };
  58260. };
  58261. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58262. var size = 512;
  58263. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58264. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58265. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58266. var context = this._randomTexture.getContext();
  58267. var rand = function (min, max) {
  58268. return Math.random() * (max - min) + min;
  58269. };
  58270. var randVector = BABYLON.Vector3.Zero();
  58271. for (var x = 0; x < size; x++) {
  58272. for (var y = 0; y < size; y++) {
  58273. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58274. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58275. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58276. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58277. context.fillRect(x, y, 1, 1);
  58278. }
  58279. }
  58280. this._randomTexture.update(false);
  58281. };
  58282. __decorate([
  58283. BABYLON.serialize()
  58284. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58285. __decorate([
  58286. BABYLON.serialize()
  58287. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58288. __decorate([
  58289. BABYLON.serialize()
  58290. ], SSAORenderingPipeline.prototype, "area", void 0);
  58291. __decorate([
  58292. BABYLON.serialize()
  58293. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58294. __decorate([
  58295. BABYLON.serialize()
  58296. ], SSAORenderingPipeline.prototype, "base", void 0);
  58297. return SSAORenderingPipeline;
  58298. }(BABYLON.PostProcessRenderPipeline));
  58299. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58300. })(BABYLON || (BABYLON = {}));
  58301. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58302. var BABYLON;
  58303. (function (BABYLON) {
  58304. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58305. __extends(SSAO2RenderingPipeline, _super);
  58306. /**
  58307. * @constructor
  58308. * @param {string} name - The rendering pipeline name
  58309. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58310. * @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 }
  58311. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58312. */
  58313. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58314. var _this = _super.call(this, scene.getEngine(), name) || this;
  58315. // Members
  58316. /**
  58317. * The PassPostProcess id in the pipeline that contains the original scene color
  58318. * @type {string}
  58319. */
  58320. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58321. /**
  58322. * The SSAO PostProcess id in the pipeline
  58323. * @type {string}
  58324. */
  58325. _this.SSAORenderEffect = "SSAORenderEffect";
  58326. /**
  58327. * The horizontal blur PostProcess id in the pipeline
  58328. * @type {string}
  58329. */
  58330. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58331. /**
  58332. * The vertical blur PostProcess id in the pipeline
  58333. * @type {string}
  58334. */
  58335. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58336. /**
  58337. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58338. * @type {string}
  58339. */
  58340. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58341. /**
  58342. * The output strength of the SSAO post-process. Default value is 1.0.
  58343. * @type {number}
  58344. */
  58345. _this.totalStrength = 1.0;
  58346. /**
  58347. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58348. * @type {number}
  58349. */
  58350. _this.maxZ = 100.0;
  58351. /**
  58352. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58353. * @type {number}
  58354. */
  58355. _this.minZAspect = 0.2;
  58356. /**
  58357. * Number of samples used for the SSAO calculations. Default value is 8
  58358. * @type {number}
  58359. */
  58360. _this._samples = 8;
  58361. /**
  58362. * Are we using bilateral blur ?
  58363. * @type {boolean}
  58364. */
  58365. _this._expensiveBlur = true;
  58366. /**
  58367. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58368. * @type {number}
  58369. */
  58370. _this.radius = 2.0;
  58371. /**
  58372. * The base color of the SSAO post-process
  58373. * The final result is "base + ssao" between [0, 1]
  58374. * @type {number}
  58375. */
  58376. _this.base = 0.1;
  58377. _this._firstUpdate = true;
  58378. _this._scene = scene;
  58379. if (!_this.isSupported) {
  58380. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58381. return _this;
  58382. }
  58383. var ssaoRatio = ratio.ssaoRatio || ratio;
  58384. var blurRatio = ratio.blurRatio || ratio;
  58385. // Set up assets
  58386. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58387. _this._createRandomTexture();
  58388. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58389. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58390. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58391. _this._createSSAOPostProcess(1.0);
  58392. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58393. _this._createSSAOCombinePostProcess(blurRatio);
  58394. // Set up pipeline
  58395. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58396. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58398. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58399. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58400. // Finish
  58401. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58402. if (cameras)
  58403. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58404. return _this;
  58405. }
  58406. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58407. get: function () {
  58408. return this._samples;
  58409. },
  58410. set: function (n) {
  58411. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58412. this._samples = n;
  58413. this._sampleSphere = this._generateHemisphere();
  58414. this._firstUpdate = true;
  58415. },
  58416. enumerable: true,
  58417. configurable: true
  58418. });
  58419. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58420. get: function () {
  58421. return this._expensiveBlur;
  58422. },
  58423. set: function (b) {
  58424. 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"]);
  58425. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58426. this._expensiveBlur = b;
  58427. this._firstUpdate = true;
  58428. },
  58429. enumerable: true,
  58430. configurable: true
  58431. });
  58432. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58433. /**
  58434. * Support test.
  58435. * @type {boolean}
  58436. */
  58437. get: function () {
  58438. var engine = BABYLON.Engine.LastCreatedEngine;
  58439. if (!engine) {
  58440. return false;
  58441. }
  58442. return engine.getCaps().drawBuffersExtension;
  58443. },
  58444. enumerable: true,
  58445. configurable: true
  58446. });
  58447. // Public Methods
  58448. /**
  58449. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58450. */
  58451. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58452. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58453. for (var i = 0; i < this._scene.cameras.length; i++) {
  58454. var camera = this._scene.cameras[i];
  58455. this._originalColorPostProcess.dispose(camera);
  58456. this._ssaoPostProcess.dispose(camera);
  58457. this._blurHPostProcess.dispose(camera);
  58458. this._blurVPostProcess.dispose(camera);
  58459. this._ssaoCombinePostProcess.dispose(camera);
  58460. }
  58461. this._randomTexture.dispose();
  58462. if (disableGeometryBufferRenderer)
  58463. this._scene.disableGeometryBufferRenderer();
  58464. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58465. _super.prototype.dispose.call(this);
  58466. };
  58467. // Private Methods
  58468. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58469. var _this = this;
  58470. this._samplerOffsets = [];
  58471. var expensive = this.expensiveBlur;
  58472. for (var i = -8; i < 8; i++) {
  58473. this._samplerOffsets.push(i * 2 + 0.5);
  58474. }
  58475. 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");
  58476. this._blurHPostProcess.onApply = function (effect) {
  58477. if (!_this._scene.activeCamera) {
  58478. return;
  58479. }
  58480. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58481. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58482. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58483. effect.setFloat("radius", _this.radius);
  58484. effect.setTexture("depthSampler", _this._depthTexture);
  58485. if (_this._firstUpdate) {
  58486. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58487. }
  58488. };
  58489. 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");
  58490. this._blurVPostProcess.onApply = function (effect) {
  58491. if (!_this._scene.activeCamera) {
  58492. return;
  58493. }
  58494. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58495. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58496. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58497. effect.setFloat("radius", _this.radius);
  58498. effect.setTexture("depthSampler", _this._depthTexture);
  58499. if (_this._firstUpdate) {
  58500. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58501. _this._firstUpdate = false;
  58502. }
  58503. };
  58504. };
  58505. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58506. this._firstUpdate = true;
  58507. _super.prototype._rebuild.call(this);
  58508. };
  58509. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58510. var numSamples = this.samples;
  58511. var result = [];
  58512. var vector, scale;
  58513. var rand = function (min, max) {
  58514. return Math.random() * (max - min) + min;
  58515. };
  58516. var i = 0;
  58517. while (i < numSamples) {
  58518. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58519. vector.normalize();
  58520. scale = i / numSamples;
  58521. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58522. vector.scaleInPlace(scale);
  58523. result.push(vector.x, vector.y, vector.z);
  58524. i++;
  58525. }
  58526. return result;
  58527. };
  58528. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58529. var _this = this;
  58530. var numSamples = this.samples;
  58531. this._sampleSphere = this._generateHemisphere();
  58532. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58533. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58534. "base", "range", "projection", "near", "far", "texelSize",
  58535. "xViewport", "yViewport", "maxZ", "minZAspect"
  58536. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58537. this._ssaoPostProcess.onApply = function (effect) {
  58538. if (_this._firstUpdate) {
  58539. effect.setArray3("sampleSphere", _this._sampleSphere);
  58540. effect.setFloat("randTextureTiles", 4.0);
  58541. }
  58542. if (!_this._scene.activeCamera) {
  58543. return;
  58544. }
  58545. effect.setFloat("samplesFactor", 1 / _this.samples);
  58546. effect.setFloat("totalStrength", _this.totalStrength);
  58547. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58548. effect.setFloat("radius", _this.radius);
  58549. effect.setFloat("maxZ", _this.maxZ);
  58550. effect.setFloat("minZAspect", _this.minZAspect);
  58551. effect.setFloat("base", _this.base);
  58552. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58553. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58554. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58555. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58556. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58557. effect.setTexture("textureSampler", _this._depthTexture);
  58558. effect.setTexture("normalSampler", _this._normalTexture);
  58559. effect.setTexture("randomSampler", _this._randomTexture);
  58560. };
  58561. };
  58562. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58563. var _this = this;
  58564. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58565. this._ssaoCombinePostProcess.onApply = function (effect) {
  58566. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58567. };
  58568. };
  58569. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58570. var size = 512;
  58571. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58572. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58573. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58574. var context = this._randomTexture.getContext();
  58575. var rand = function (min, max) {
  58576. return Math.random() * (max - min) + min;
  58577. };
  58578. var randVector = BABYLON.Vector3.Zero();
  58579. for (var x = 0; x < size; x++) {
  58580. for (var y = 0; y < size; y++) {
  58581. randVector.x = rand(0.0, 1.0);
  58582. randVector.y = rand(0.0, 1.0);
  58583. randVector.z = 0.0;
  58584. randVector.normalize();
  58585. randVector.scaleInPlace(255);
  58586. randVector.x = Math.floor(randVector.x);
  58587. randVector.y = Math.floor(randVector.y);
  58588. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58589. context.fillRect(x, y, 1, 1);
  58590. }
  58591. }
  58592. this._randomTexture.update(false);
  58593. };
  58594. __decorate([
  58595. BABYLON.serialize()
  58596. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58597. __decorate([
  58598. BABYLON.serialize()
  58599. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58600. __decorate([
  58601. BABYLON.serialize()
  58602. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58603. __decorate([
  58604. BABYLON.serialize("samples")
  58605. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58606. __decorate([
  58607. BABYLON.serialize("expensiveBlur")
  58608. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58609. __decorate([
  58610. BABYLON.serialize()
  58611. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58612. __decorate([
  58613. BABYLON.serialize()
  58614. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58615. return SSAO2RenderingPipeline;
  58616. }(BABYLON.PostProcessRenderPipeline));
  58617. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58618. })(BABYLON || (BABYLON = {}));
  58619. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58620. // BABYLON.JS Chromatic Aberration GLSL Shader
  58621. // Author: Olivier Guyot
  58622. // Separates very slightly R, G and B colors on the edges of the screen
  58623. // Inspired by Francois Tarlier & Martins Upitis
  58624. var BABYLON;
  58625. (function (BABYLON) {
  58626. var LensRenderingPipeline = /** @class */ (function (_super) {
  58627. __extends(LensRenderingPipeline, _super);
  58628. /**
  58629. * @constructor
  58630. *
  58631. * Effect parameters are as follow:
  58632. * {
  58633. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58634. * edge_blur: number; // from 0 to x (1 for realism)
  58635. * distortion: number; // from 0 to x (1 for realism)
  58636. * grain_amount: number; // from 0 to 1
  58637. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58638. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58639. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58640. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58641. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58642. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58643. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58644. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58645. * }
  58646. * Note: if an effect parameter is unset, effect is disabled
  58647. *
  58648. * @param {string} name - The rendering pipeline name
  58649. * @param {object} parameters - An object containing all parameters (see above)
  58650. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58651. * @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)
  58652. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58653. */
  58654. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58655. if (ratio === void 0) { ratio = 1.0; }
  58656. var _this = _super.call(this, scene.getEngine(), name) || this;
  58657. // Lens effects can be of the following:
  58658. // - chromatic aberration (slight shift of RGB colors)
  58659. // - blur on the edge of the lens
  58660. // - lens distortion
  58661. // - depth-of-field blur & highlights enhancing
  58662. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58663. // - grain effect (noise or custom texture)
  58664. // Two additional texture samplers are needed:
  58665. // - depth map (for depth-of-field)
  58666. // - grain texture
  58667. /**
  58668. * The chromatic aberration PostProcess id in the pipeline
  58669. * @type {string}
  58670. */
  58671. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58672. /**
  58673. * The highlights enhancing PostProcess id in the pipeline
  58674. * @type {string}
  58675. */
  58676. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58677. /**
  58678. * The depth-of-field PostProcess id in the pipeline
  58679. * @type {string}
  58680. */
  58681. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58682. _this._scene = scene;
  58683. // Fetch texture samplers
  58684. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58685. if (parameters.grain_texture) {
  58686. _this._grainTexture = parameters.grain_texture;
  58687. }
  58688. else {
  58689. _this._createGrainTexture();
  58690. }
  58691. // save parameters
  58692. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58693. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58694. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58695. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58696. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58697. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58698. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58699. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58700. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58701. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58702. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58703. // Create effects
  58704. _this._createChromaticAberrationPostProcess(ratio);
  58705. _this._createHighlightsPostProcess(ratio);
  58706. _this._createDepthOfFieldPostProcess(ratio / 4);
  58707. // Set up pipeline
  58708. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58709. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58710. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58711. if (_this._highlightsGain === -1) {
  58712. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58713. }
  58714. // Finish
  58715. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58716. if (cameras) {
  58717. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58718. }
  58719. return _this;
  58720. }
  58721. // public methods (self explanatory)
  58722. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58723. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58724. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58725. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58726. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58727. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58728. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58729. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58730. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58731. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58732. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58733. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58734. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58735. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58736. };
  58737. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58738. this._highlightsPostProcess.updateEffect();
  58739. };
  58740. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58741. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58742. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58743. this._highlightsGain = amount;
  58744. };
  58745. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58746. if (this._highlightsGain === -1) {
  58747. this._highlightsGain = 1.0;
  58748. }
  58749. this._highlightsThreshold = amount;
  58750. };
  58751. LensRenderingPipeline.prototype.disableHighlights = function () {
  58752. this._highlightsGain = -1;
  58753. };
  58754. /**
  58755. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58756. */
  58757. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58758. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58759. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58760. this._chromaticAberrationPostProcess = null;
  58761. this._highlightsPostProcess = null;
  58762. this._depthOfFieldPostProcess = null;
  58763. this._grainTexture.dispose();
  58764. if (disableDepthRender)
  58765. this._scene.disableDepthRenderer();
  58766. };
  58767. // colors shifting and distortion
  58768. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58769. var _this = this;
  58770. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58771. [], // samplers
  58772. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58773. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58774. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58775. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58776. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58777. };
  58778. };
  58779. // highlights enhancing
  58780. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58781. var _this = this;
  58782. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58783. [], // samplers
  58784. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58785. this._highlightsPostProcess.onApply = function (effect) {
  58786. effect.setFloat('gain', _this._highlightsGain);
  58787. effect.setFloat('threshold', _this._highlightsThreshold);
  58788. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58789. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58790. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58791. };
  58792. };
  58793. // colors shifting and distortion
  58794. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58795. var _this = this;
  58796. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58797. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58798. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58799. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58800. this._depthOfFieldPostProcess.onApply = function (effect) {
  58801. effect.setTexture("depthSampler", _this._depthTexture);
  58802. effect.setTexture("grainSampler", _this._grainTexture);
  58803. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58804. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58805. effect.setFloat('grain_amount', _this._grainAmount);
  58806. effect.setBool('blur_noise', _this._blurNoise);
  58807. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58808. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58809. effect.setFloat('distortion', _this._distortion);
  58810. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58811. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58812. effect.setFloat('aperture', _this._dofAperture);
  58813. effect.setFloat('darken', _this._dofDarken);
  58814. effect.setFloat('edge_blur', _this._edgeBlur);
  58815. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58816. if (_this._scene.activeCamera) {
  58817. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58818. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58819. }
  58820. };
  58821. };
  58822. // creates a black and white random noise texture, 512x512
  58823. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58824. var size = 512;
  58825. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58826. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58827. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58828. var context = this._grainTexture.getContext();
  58829. var rand = function (min, max) {
  58830. return Math.random() * (max - min) + min;
  58831. };
  58832. var value;
  58833. for (var x = 0; x < size; x++) {
  58834. for (var y = 0; y < size; y++) {
  58835. value = Math.floor(rand(0.42, 0.58) * 255);
  58836. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58837. context.fillRect(x, y, 1, 1);
  58838. }
  58839. }
  58840. this._grainTexture.update(false);
  58841. };
  58842. return LensRenderingPipeline;
  58843. }(BABYLON.PostProcessRenderPipeline));
  58844. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58845. })(BABYLON || (BABYLON = {}));
  58846. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58847. var BABYLON;
  58848. (function (BABYLON) {
  58849. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58850. __extends(StandardRenderingPipeline, _super);
  58851. /**
  58852. * @constructor
  58853. * @param {string} name - The rendering pipeline name
  58854. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58855. * @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)
  58856. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58857. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58858. */
  58859. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58860. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58861. var _this = _super.call(this, scene.getEngine(), name) || this;
  58862. _this.downSampleX4PostProcess = null;
  58863. _this.brightPassPostProcess = null;
  58864. _this.blurHPostProcesses = [];
  58865. _this.blurVPostProcesses = [];
  58866. _this.textureAdderPostProcess = null;
  58867. _this.volumetricLightPostProcess = null;
  58868. _this.volumetricLightSmoothXPostProcess = null;
  58869. _this.volumetricLightSmoothYPostProcess = null;
  58870. _this.volumetricLightMergePostProces = null;
  58871. _this.volumetricLightFinalPostProcess = null;
  58872. _this.luminancePostProcess = null;
  58873. _this.luminanceDownSamplePostProcesses = [];
  58874. _this.hdrPostProcess = null;
  58875. _this.textureAdderFinalPostProcess = null;
  58876. _this.lensFlareFinalPostProcess = null;
  58877. _this.hdrFinalPostProcess = null;
  58878. _this.lensFlarePostProcess = null;
  58879. _this.lensFlareComposePostProcess = null;
  58880. _this.motionBlurPostProcess = null;
  58881. _this.depthOfFieldPostProcess = null;
  58882. // Values
  58883. _this.brightThreshold = 1.0;
  58884. _this.blurWidth = 512.0;
  58885. _this.horizontalBlur = false;
  58886. _this.exposure = 1.0;
  58887. _this.lensTexture = null;
  58888. _this.volumetricLightCoefficient = 0.2;
  58889. _this.volumetricLightPower = 4.0;
  58890. _this.volumetricLightBlurScale = 64.0;
  58891. _this.sourceLight = null;
  58892. _this.hdrMinimumLuminance = 1.0;
  58893. _this.hdrDecreaseRate = 0.5;
  58894. _this.hdrIncreaseRate = 0.5;
  58895. _this.lensColorTexture = null;
  58896. _this.lensFlareStrength = 20.0;
  58897. _this.lensFlareGhostDispersal = 1.4;
  58898. _this.lensFlareHaloWidth = 0.7;
  58899. _this.lensFlareDistortionStrength = 16.0;
  58900. _this.lensStarTexture = null;
  58901. _this.lensFlareDirtTexture = null;
  58902. _this.depthOfFieldDistance = 10.0;
  58903. _this.depthOfFieldBlurWidth = 64.0;
  58904. _this.motionStrength = 1.0;
  58905. // IAnimatable
  58906. _this.animations = [];
  58907. _this._currentDepthOfFieldSource = null;
  58908. _this._hdrCurrentLuminance = 1.0;
  58909. // Getters and setters
  58910. _this._bloomEnabled = true;
  58911. _this._depthOfFieldEnabled = false;
  58912. _this._vlsEnabled = false;
  58913. _this._lensFlareEnabled = false;
  58914. _this._hdrEnabled = false;
  58915. _this._motionBlurEnabled = false;
  58916. _this._motionBlurSamples = 64.0;
  58917. _this._volumetricLightStepsCount = 50.0;
  58918. _this._cameras = cameras || [];
  58919. // Initialize
  58920. _this._scene = scene;
  58921. _this._basePostProcess = originalPostProcess;
  58922. _this._ratio = ratio;
  58923. // Misc
  58924. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58925. // Finish
  58926. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58927. _this._buildPipeline();
  58928. return _this;
  58929. }
  58930. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58931. get: function () {
  58932. return this._bloomEnabled;
  58933. },
  58934. set: function (enabled) {
  58935. if (this._bloomEnabled === enabled) {
  58936. return;
  58937. }
  58938. this._bloomEnabled = enabled;
  58939. this._buildPipeline();
  58940. },
  58941. enumerable: true,
  58942. configurable: true
  58943. });
  58944. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58945. get: function () {
  58946. return this._depthOfFieldEnabled;
  58947. },
  58948. set: function (enabled) {
  58949. if (this._depthOfFieldEnabled === enabled) {
  58950. return;
  58951. }
  58952. this._depthOfFieldEnabled = enabled;
  58953. this._buildPipeline();
  58954. },
  58955. enumerable: true,
  58956. configurable: true
  58957. });
  58958. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58959. get: function () {
  58960. return this._lensFlareEnabled;
  58961. },
  58962. set: function (enabled) {
  58963. if (this._lensFlareEnabled === enabled) {
  58964. return;
  58965. }
  58966. this._lensFlareEnabled = enabled;
  58967. this._buildPipeline();
  58968. },
  58969. enumerable: true,
  58970. configurable: true
  58971. });
  58972. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58973. get: function () {
  58974. return this._hdrEnabled;
  58975. },
  58976. set: function (enabled) {
  58977. if (this._hdrEnabled === enabled) {
  58978. return;
  58979. }
  58980. this._hdrEnabled = enabled;
  58981. this._buildPipeline();
  58982. },
  58983. enumerable: true,
  58984. configurable: true
  58985. });
  58986. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58987. get: function () {
  58988. return this._vlsEnabled;
  58989. },
  58990. set: function (enabled) {
  58991. if (this._vlsEnabled === enabled) {
  58992. return;
  58993. }
  58994. if (enabled) {
  58995. var geometry = this._scene.enableGeometryBufferRenderer();
  58996. if (!geometry) {
  58997. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58998. return;
  58999. }
  59000. }
  59001. this._vlsEnabled = enabled;
  59002. this._buildPipeline();
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59008. get: function () {
  59009. return this._motionBlurEnabled;
  59010. },
  59011. set: function (enabled) {
  59012. if (this._motionBlurEnabled === enabled) {
  59013. return;
  59014. }
  59015. this._motionBlurEnabled = enabled;
  59016. this._buildPipeline();
  59017. },
  59018. enumerable: true,
  59019. configurable: true
  59020. });
  59021. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59022. get: function () {
  59023. return this._volumetricLightStepsCount;
  59024. },
  59025. set: function (count) {
  59026. if (this.volumetricLightPostProcess) {
  59027. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59028. }
  59029. this._volumetricLightStepsCount = count;
  59030. },
  59031. enumerable: true,
  59032. configurable: true
  59033. });
  59034. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59035. get: function () {
  59036. return this._motionBlurSamples;
  59037. },
  59038. set: function (samples) {
  59039. if (this.motionBlurPostProcess) {
  59040. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59041. }
  59042. this._motionBlurSamples = samples;
  59043. },
  59044. enumerable: true,
  59045. configurable: true
  59046. });
  59047. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59048. var _this = this;
  59049. var ratio = this._ratio;
  59050. var scene = this._scene;
  59051. this._disposePostProcesses();
  59052. this._reset();
  59053. // Create pass post-process
  59054. if (!this._basePostProcess) {
  59055. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59056. this.originalPostProcess.onApply = function (effect) {
  59057. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59058. };
  59059. }
  59060. else {
  59061. this.originalPostProcess = this._basePostProcess;
  59062. }
  59063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59064. this._currentDepthOfFieldSource = this.originalPostProcess;
  59065. if (this._vlsEnabled) {
  59066. // Create volumetric light
  59067. this._createVolumetricLightPostProcess(scene, ratio);
  59068. // Create volumetric light final post-process
  59069. 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);
  59070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59071. }
  59072. if (this._bloomEnabled) {
  59073. // Create down sample X4 post-process
  59074. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59075. // Create bright pass post-process
  59076. this._createBrightPassPostProcess(scene, ratio / 2);
  59077. // Create gaussian blur post-processes (down sampling blurs)
  59078. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59079. // Create texture adder post-process
  59080. this._createTextureAdderPostProcess(scene, ratio);
  59081. // Create depth-of-field source post-process
  59082. 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);
  59083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59084. }
  59085. if (this._lensFlareEnabled) {
  59086. // Create lens flare post-process
  59087. this._createLensFlarePostProcess(scene, ratio);
  59088. // Create depth-of-field source post-process post lens-flare and disable it now
  59089. 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);
  59090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59091. }
  59092. if (this._hdrEnabled) {
  59093. // Create luminance
  59094. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59095. // Create HDR
  59096. this._createHdrPostProcess(scene, ratio);
  59097. // Create depth-of-field source post-process post hdr and disable it now
  59098. 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);
  59099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59100. }
  59101. if (this._depthOfFieldEnabled) {
  59102. // Create gaussian blur used by depth-of-field
  59103. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59104. // Create depth-of-field post-process
  59105. this._createDepthOfFieldPostProcess(scene, ratio);
  59106. }
  59107. if (this._motionBlurEnabled) {
  59108. // Create motion blur post-process
  59109. this._createMotionBlurPostProcess(scene, ratio);
  59110. }
  59111. if (this._cameras !== null) {
  59112. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59113. }
  59114. };
  59115. // Down Sample X4 Post-Processs
  59116. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59117. var _this = this;
  59118. var downSampleX4Offsets = new Array(32);
  59119. 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);
  59120. this.downSampleX4PostProcess.onApply = function (effect) {
  59121. var id = 0;
  59122. var width = _this.downSampleX4PostProcess.width;
  59123. var height = _this.downSampleX4PostProcess.height;
  59124. for (var i = -2; i < 2; i++) {
  59125. for (var j = -2; j < 2; j++) {
  59126. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59127. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59128. id += 2;
  59129. }
  59130. }
  59131. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59132. };
  59133. // Add to pipeline
  59134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59135. };
  59136. // Brightpass Post-Process
  59137. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59138. var _this = this;
  59139. var brightOffsets = new Array(8);
  59140. 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);
  59141. this.brightPassPostProcess.onApply = function (effect) {
  59142. var sU = (1.0 / _this.brightPassPostProcess.width);
  59143. var sV = (1.0 / _this.brightPassPostProcess.height);
  59144. brightOffsets[0] = -0.5 * sU;
  59145. brightOffsets[1] = 0.5 * sV;
  59146. brightOffsets[2] = 0.5 * sU;
  59147. brightOffsets[3] = 0.5 * sV;
  59148. brightOffsets[4] = -0.5 * sU;
  59149. brightOffsets[5] = -0.5 * sV;
  59150. brightOffsets[6] = 0.5 * sU;
  59151. brightOffsets[7] = -0.5 * sV;
  59152. effect.setArray2("dsOffsets", brightOffsets);
  59153. effect.setFloat("brightThreshold", _this.brightThreshold);
  59154. };
  59155. // Add to pipeline
  59156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59157. };
  59158. // Create blur H&V post-processes
  59159. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59160. var _this = this;
  59161. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59162. var engine = scene.getEngine();
  59163. 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);
  59164. 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);
  59165. blurX.onActivateObservable.add(function () {
  59166. var dw = blurX.width / engine.getRenderWidth();
  59167. blurX.kernel = _this[blurWidthKey] * dw;
  59168. });
  59169. blurY.onActivateObservable.add(function () {
  59170. var dw = blurY.height / engine.getRenderHeight();
  59171. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59172. });
  59173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59175. this.blurHPostProcesses.push(blurX);
  59176. this.blurVPostProcesses.push(blurY);
  59177. };
  59178. // Create texture adder post-process
  59179. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59180. var _this = this;
  59181. 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);
  59182. this.textureAdderPostProcess.onApply = function (effect) {
  59183. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59184. effect.setTexture("lensSampler", _this.lensTexture);
  59185. effect.setFloat("exposure", _this.exposure);
  59186. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59187. };
  59188. // Add to pipeline
  59189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59190. };
  59191. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59192. var _this = this;
  59193. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59194. geometryRenderer.enablePosition = true;
  59195. var geometry = geometryRenderer.getGBuffer();
  59196. // Base post-process
  59197. 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));
  59198. var depthValues = BABYLON.Vector2.Zero();
  59199. this.volumetricLightPostProcess.onApply = function (effect) {
  59200. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59201. var generator = _this.sourceLight.getShadowGenerator();
  59202. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59203. effect.setTexture("positionSampler", geometry.textures[2]);
  59204. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59205. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59206. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59207. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59208. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59209. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59210. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59211. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59212. effect.setVector2("depthValues", depthValues);
  59213. }
  59214. };
  59215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59216. // Smooth
  59217. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59218. // Merge
  59219. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59220. this.volumetricLightMergePostProces.onApply = function (effect) {
  59221. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59222. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59223. };
  59224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59225. };
  59226. // Create luminance
  59227. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59228. var _this = this;
  59229. // Create luminance
  59230. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59231. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59232. var offsets = [];
  59233. this.luminancePostProcess.onApply = function (effect) {
  59234. var sU = (1.0 / _this.luminancePostProcess.width);
  59235. var sV = (1.0 / _this.luminancePostProcess.height);
  59236. offsets[0] = -0.5 * sU;
  59237. offsets[1] = 0.5 * sV;
  59238. offsets[2] = 0.5 * sU;
  59239. offsets[3] = 0.5 * sV;
  59240. offsets[4] = -0.5 * sU;
  59241. offsets[5] = -0.5 * sV;
  59242. offsets[6] = 0.5 * sU;
  59243. offsets[7] = -0.5 * sV;
  59244. effect.setArray2("lumOffsets", offsets);
  59245. };
  59246. // Add to pipeline
  59247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59248. // Create down sample luminance
  59249. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59250. var size = Math.pow(3, i);
  59251. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59252. if (i === 0) {
  59253. defines += "#define FINAL_DOWN_SAMPLER";
  59254. }
  59255. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59256. this.luminanceDownSamplePostProcesses.push(postProcess);
  59257. }
  59258. // Create callbacks and add effects
  59259. var lastLuminance = this.luminancePostProcess;
  59260. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59261. var downSampleOffsets = new Array(18);
  59262. pp.onApply = function (effect) {
  59263. if (!lastLuminance) {
  59264. return;
  59265. }
  59266. var id = 0;
  59267. for (var x = -1; x < 2; x++) {
  59268. for (var y = -1; y < 2; y++) {
  59269. downSampleOffsets[id] = x / lastLuminance.width;
  59270. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59271. id += 2;
  59272. }
  59273. }
  59274. effect.setArray2("dsOffsets", downSampleOffsets);
  59275. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59276. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59277. lastLuminance = _this.luminancePostProcess;
  59278. }
  59279. else {
  59280. lastLuminance = pp;
  59281. }
  59282. };
  59283. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59284. pp.onAfterRender = function (effect) {
  59285. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59286. 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);
  59287. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59288. };
  59289. }
  59290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59291. });
  59292. };
  59293. // Create HDR post-process
  59294. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59295. var _this = this;
  59296. 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);
  59297. var outputLiminance = 1;
  59298. var time = 0;
  59299. var lastTime = 0;
  59300. this.hdrPostProcess.onApply = function (effect) {
  59301. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59302. time += scene.getEngine().getDeltaTime();
  59303. if (outputLiminance < 0) {
  59304. outputLiminance = _this._hdrCurrentLuminance;
  59305. }
  59306. else {
  59307. var dt = (lastTime - time) / 1000.0;
  59308. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59309. outputLiminance += _this.hdrDecreaseRate * dt;
  59310. }
  59311. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59312. outputLiminance -= _this.hdrIncreaseRate * dt;
  59313. }
  59314. else {
  59315. outputLiminance = _this._hdrCurrentLuminance;
  59316. }
  59317. }
  59318. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59319. effect.setFloat("averageLuminance", outputLiminance);
  59320. lastTime = time;
  59321. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59322. };
  59323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59324. };
  59325. // Create lens flare post-process
  59326. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59327. var _this = this;
  59328. 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);
  59329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59330. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59331. 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);
  59332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59333. var resolution = new BABYLON.Vector2(0, 0);
  59334. // Lens flare
  59335. this.lensFlarePostProcess.onApply = function (effect) {
  59336. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59337. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59338. effect.setFloat("strength", _this.lensFlareStrength);
  59339. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59340. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59341. // Shift
  59342. resolution.x = _this.lensFlarePostProcess.width;
  59343. resolution.y = _this.lensFlarePostProcess.height;
  59344. effect.setVector2("resolution", resolution);
  59345. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59346. };
  59347. // Compose
  59348. 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);
  59349. 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);
  59350. this.lensFlareComposePostProcess.onApply = function (effect) {
  59351. if (!_this._scene.activeCamera) {
  59352. return;
  59353. }
  59354. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59355. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59356. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59357. // Lens start rotation matrix
  59358. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59359. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59360. 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));
  59361. camRot *= 4.0;
  59362. 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);
  59363. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59364. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59365. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59366. };
  59367. };
  59368. // Create depth-of-field post-process
  59369. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59370. var _this = this;
  59371. 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);
  59372. this.depthOfFieldPostProcess.onApply = function (effect) {
  59373. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59374. effect.setTexture("depthSampler", _this._getDepthTexture());
  59375. effect.setFloat("distance", _this.depthOfFieldDistance);
  59376. };
  59377. // Add to pipeline
  59378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59379. };
  59380. // Create motion blur post-process
  59381. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59382. var _this = this;
  59383. 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);
  59384. var motionScale = 0;
  59385. var prevViewProjection = BABYLON.Matrix.Identity();
  59386. var invViewProjection = BABYLON.Matrix.Identity();
  59387. var viewProjection = BABYLON.Matrix.Identity();
  59388. var screenSize = BABYLON.Vector2.Zero();
  59389. this.motionBlurPostProcess.onApply = function (effect) {
  59390. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59391. viewProjection.invertToRef(invViewProjection);
  59392. effect.setMatrix("inverseViewProjection", invViewProjection);
  59393. effect.setMatrix("prevViewProjection", prevViewProjection);
  59394. prevViewProjection = viewProjection;
  59395. screenSize.x = _this.motionBlurPostProcess.width;
  59396. screenSize.y = _this.motionBlurPostProcess.height;
  59397. effect.setVector2("screenSize", screenSize);
  59398. motionScale = scene.getEngine().getFps() / 60.0;
  59399. effect.setFloat("motionScale", motionScale);
  59400. effect.setFloat("motionStrength", _this.motionStrength);
  59401. effect.setTexture("depthSampler", _this._getDepthTexture());
  59402. };
  59403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59404. };
  59405. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59406. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59407. var renderer = this._scene.enableGeometryBufferRenderer();
  59408. return renderer.getGBuffer().textures[0];
  59409. }
  59410. return this._scene.enableDepthRenderer().getDepthMap();
  59411. };
  59412. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59413. for (var i = 0; i < this._cameras.length; i++) {
  59414. var camera = this._cameras[i];
  59415. if (this.originalPostProcess) {
  59416. this.originalPostProcess.dispose(camera);
  59417. }
  59418. if (this.downSampleX4PostProcess) {
  59419. this.downSampleX4PostProcess.dispose(camera);
  59420. }
  59421. if (this.brightPassPostProcess) {
  59422. this.brightPassPostProcess.dispose(camera);
  59423. }
  59424. if (this.textureAdderPostProcess) {
  59425. this.textureAdderPostProcess.dispose(camera);
  59426. }
  59427. if (this.textureAdderFinalPostProcess) {
  59428. this.textureAdderFinalPostProcess.dispose(camera);
  59429. }
  59430. if (this.volumetricLightPostProcess) {
  59431. this.volumetricLightPostProcess.dispose(camera);
  59432. }
  59433. if (this.volumetricLightSmoothXPostProcess) {
  59434. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59435. }
  59436. if (this.volumetricLightSmoothYPostProcess) {
  59437. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59438. }
  59439. if (this.volumetricLightMergePostProces) {
  59440. this.volumetricLightMergePostProces.dispose(camera);
  59441. }
  59442. if (this.volumetricLightFinalPostProcess) {
  59443. this.volumetricLightFinalPostProcess.dispose(camera);
  59444. }
  59445. if (this.lensFlarePostProcess) {
  59446. this.lensFlarePostProcess.dispose(camera);
  59447. }
  59448. if (this.lensFlareComposePostProcess) {
  59449. this.lensFlareComposePostProcess.dispose(camera);
  59450. }
  59451. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59452. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59453. }
  59454. if (this.luminancePostProcess) {
  59455. this.luminancePostProcess.dispose(camera);
  59456. }
  59457. if (this.hdrPostProcess) {
  59458. this.hdrPostProcess.dispose(camera);
  59459. }
  59460. if (this.hdrFinalPostProcess) {
  59461. this.hdrFinalPostProcess.dispose(camera);
  59462. }
  59463. if (this.depthOfFieldPostProcess) {
  59464. this.depthOfFieldPostProcess.dispose(camera);
  59465. }
  59466. if (this.motionBlurPostProcess) {
  59467. this.motionBlurPostProcess.dispose(camera);
  59468. }
  59469. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59470. this.blurHPostProcesses[j].dispose(camera);
  59471. }
  59472. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59473. this.blurVPostProcesses[j].dispose(camera);
  59474. }
  59475. }
  59476. this.originalPostProcess = null;
  59477. this.downSampleX4PostProcess = null;
  59478. this.brightPassPostProcess = null;
  59479. this.textureAdderPostProcess = null;
  59480. this.textureAdderFinalPostProcess = null;
  59481. this.volumetricLightPostProcess = null;
  59482. this.volumetricLightSmoothXPostProcess = null;
  59483. this.volumetricLightSmoothYPostProcess = null;
  59484. this.volumetricLightMergePostProces = null;
  59485. this.volumetricLightFinalPostProcess = null;
  59486. this.lensFlarePostProcess = null;
  59487. this.lensFlareComposePostProcess = null;
  59488. this.luminancePostProcess = null;
  59489. this.hdrPostProcess = null;
  59490. this.hdrFinalPostProcess = null;
  59491. this.depthOfFieldPostProcess = null;
  59492. this.motionBlurPostProcess = null;
  59493. this.luminanceDownSamplePostProcesses = [];
  59494. this.blurHPostProcesses = [];
  59495. this.blurVPostProcesses = [];
  59496. };
  59497. // Dispose
  59498. StandardRenderingPipeline.prototype.dispose = function () {
  59499. this._disposePostProcesses();
  59500. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59501. _super.prototype.dispose.call(this);
  59502. };
  59503. // Serialize rendering pipeline
  59504. StandardRenderingPipeline.prototype.serialize = function () {
  59505. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59506. serializationObject.customType = "StandardRenderingPipeline";
  59507. return serializationObject;
  59508. };
  59509. /**
  59510. * Static members
  59511. */
  59512. // Parse serialized pipeline
  59513. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59514. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59515. };
  59516. // Luminance steps
  59517. StandardRenderingPipeline.LuminanceSteps = 6;
  59518. __decorate([
  59519. BABYLON.serialize()
  59520. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59521. __decorate([
  59522. BABYLON.serialize()
  59523. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59524. __decorate([
  59525. BABYLON.serialize()
  59526. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59527. __decorate([
  59528. BABYLON.serialize()
  59529. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59530. __decorate([
  59531. BABYLON.serializeAsTexture("lensTexture")
  59532. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59533. __decorate([
  59534. BABYLON.serialize()
  59535. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59536. __decorate([
  59537. BABYLON.serialize()
  59538. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59539. __decorate([
  59540. BABYLON.serialize()
  59541. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59542. __decorate([
  59543. BABYLON.serialize()
  59544. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59545. __decorate([
  59546. BABYLON.serialize()
  59547. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59548. __decorate([
  59549. BABYLON.serialize()
  59550. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59551. __decorate([
  59552. BABYLON.serializeAsTexture("lensColorTexture")
  59553. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59554. __decorate([
  59555. BABYLON.serialize()
  59556. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59557. __decorate([
  59558. BABYLON.serialize()
  59559. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59560. __decorate([
  59561. BABYLON.serialize()
  59562. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59563. __decorate([
  59564. BABYLON.serialize()
  59565. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59566. __decorate([
  59567. BABYLON.serializeAsTexture("lensStarTexture")
  59568. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59569. __decorate([
  59570. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59571. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59572. __decorate([
  59573. BABYLON.serialize()
  59574. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59575. __decorate([
  59576. BABYLON.serialize()
  59577. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59578. __decorate([
  59579. BABYLON.serialize()
  59580. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59581. __decorate([
  59582. BABYLON.serialize()
  59583. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59584. __decorate([
  59585. BABYLON.serialize()
  59586. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59587. __decorate([
  59588. BABYLON.serialize()
  59589. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59590. __decorate([
  59591. BABYLON.serialize()
  59592. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59593. __decorate([
  59594. BABYLON.serialize()
  59595. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59596. __decorate([
  59597. BABYLON.serialize()
  59598. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59599. __decorate([
  59600. BABYLON.serialize()
  59601. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59602. __decorate([
  59603. BABYLON.serialize()
  59604. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59605. return StandardRenderingPipeline;
  59606. }(BABYLON.PostProcessRenderPipeline));
  59607. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59608. })(BABYLON || (BABYLON = {}));
  59609. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59610. var BABYLON;
  59611. (function (BABYLON) {
  59612. var FxaaPostProcess = /** @class */ (function (_super) {
  59613. __extends(FxaaPostProcess, _super);
  59614. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59615. if (camera === void 0) { camera = null; }
  59616. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59617. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59618. _this.onApplyObservable.add(function (effect) {
  59619. var texelSize = _this.texelSize;
  59620. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59621. });
  59622. return _this;
  59623. }
  59624. return FxaaPostProcess;
  59625. }(BABYLON.PostProcess));
  59626. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59627. })(BABYLON || (BABYLON = {}));
  59628. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59629. var BABYLON;
  59630. (function (BABYLON) {
  59631. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59632. __extends(DefaultRenderingPipeline, _super);
  59633. /**
  59634. * @constructor
  59635. * @param {string} name - The rendering pipeline name
  59636. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59637. * @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)
  59638. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59639. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59640. */
  59641. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59642. if (automaticBuild === void 0) { automaticBuild = true; }
  59643. var _this = _super.call(this, scene.getEngine(), name) || this;
  59644. _this.PassPostProcessId = "PassPostProcessEffect";
  59645. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59646. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59647. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59648. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59649. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59650. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59651. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59652. // IAnimatable
  59653. _this.animations = [];
  59654. // Values
  59655. _this._bloomEnabled = false;
  59656. _this._fxaaEnabled = false;
  59657. _this._imageProcessingEnabled = true;
  59658. _this._bloomScale = 0.6;
  59659. _this._buildAllowed = true;
  59660. /**
  59661. * Specifies the size of the bloom blur kernel, relative to the final output size
  59662. */
  59663. _this.bloomKernel = 64;
  59664. /**
  59665. * Specifies the weight of the bloom in the final rendering
  59666. */
  59667. _this._bloomWeight = 0.15;
  59668. _this._cameras = cameras || [];
  59669. _this._buildAllowed = automaticBuild;
  59670. // Initialize
  59671. _this._scene = scene;
  59672. var caps = _this._scene.getEngine().getCaps();
  59673. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59674. // Misc
  59675. if (_this._hdr) {
  59676. if (caps.textureHalfFloatRender) {
  59677. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59678. }
  59679. else if (caps.textureFloatRender) {
  59680. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59681. }
  59682. }
  59683. else {
  59684. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59685. }
  59686. // Attach
  59687. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59688. _this._buildPipeline();
  59689. return _this;
  59690. }
  59691. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59692. get: function () {
  59693. return this._bloomWeight;
  59694. },
  59695. set: function (value) {
  59696. if (this._bloomWeight === value) {
  59697. return;
  59698. }
  59699. this._bloomWeight = value;
  59700. if (this._hdr && this.copyBack) {
  59701. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59702. }
  59703. },
  59704. enumerable: true,
  59705. configurable: true
  59706. });
  59707. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59708. get: function () {
  59709. return this._bloomScale;
  59710. },
  59711. set: function (value) {
  59712. if (this._bloomScale === value) {
  59713. return;
  59714. }
  59715. this._bloomScale = value;
  59716. this._buildPipeline();
  59717. },
  59718. enumerable: true,
  59719. configurable: true
  59720. });
  59721. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59722. get: function () {
  59723. return this._bloomEnabled;
  59724. },
  59725. set: function (enabled) {
  59726. if (this._bloomEnabled === enabled) {
  59727. return;
  59728. }
  59729. this._bloomEnabled = enabled;
  59730. this._buildPipeline();
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59736. get: function () {
  59737. return this._fxaaEnabled;
  59738. },
  59739. set: function (enabled) {
  59740. if (this._fxaaEnabled === enabled) {
  59741. return;
  59742. }
  59743. this._fxaaEnabled = enabled;
  59744. this._buildPipeline();
  59745. },
  59746. enumerable: true,
  59747. configurable: true
  59748. });
  59749. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59750. get: function () {
  59751. return this._imageProcessingEnabled;
  59752. },
  59753. set: function (enabled) {
  59754. if (this._imageProcessingEnabled === enabled) {
  59755. return;
  59756. }
  59757. this._imageProcessingEnabled = enabled;
  59758. this._buildPipeline();
  59759. },
  59760. enumerable: true,
  59761. configurable: true
  59762. });
  59763. /**
  59764. * Force the compilation of the entire pipeline.
  59765. */
  59766. DefaultRenderingPipeline.prototype.prepare = function () {
  59767. var previousState = this._buildAllowed;
  59768. this._buildAllowed = true;
  59769. this._buildPipeline();
  59770. this._buildAllowed = previousState;
  59771. };
  59772. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59773. var _this = this;
  59774. if (!this._buildAllowed) {
  59775. return;
  59776. }
  59777. var engine = this._scene.getEngine();
  59778. this._disposePostProcesses();
  59779. this._reset();
  59780. if (this.bloomEnabled) {
  59781. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59782. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59783. if (!this._hdr) {
  59784. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59785. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59786. this.highlights.autoClear = false;
  59787. this.highlights.alwaysForcePOT = true;
  59788. }
  59789. 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);
  59790. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59791. this.blurX.alwaysForcePOT = true;
  59792. this.blurX.autoClear = false;
  59793. this.blurX.onActivateObservable.add(function () {
  59794. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59795. _this.blurX.kernel = _this.bloomKernel * dw;
  59796. });
  59797. 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);
  59798. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59799. this.blurY.alwaysForcePOT = true;
  59800. this.blurY.autoClear = false;
  59801. this.blurY.onActivateObservable.add(function () {
  59802. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59803. _this.blurY.kernel = _this.bloomKernel * dh;
  59804. });
  59805. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59806. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59807. this.copyBack.alwaysForcePOT = true;
  59808. if (this._hdr) {
  59809. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59810. var w = this.bloomWeight;
  59811. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59812. }
  59813. else {
  59814. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59815. }
  59816. this.copyBack.autoClear = false;
  59817. }
  59818. if (this._imageProcessingEnabled) {
  59819. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59820. if (this._hdr) {
  59821. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59822. }
  59823. else {
  59824. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59825. }
  59826. }
  59827. if (this.fxaaEnabled) {
  59828. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59829. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59830. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59831. }
  59832. else if (this._hdr && this.imageProcessing) {
  59833. this.finalMerge = this.imageProcessing;
  59834. }
  59835. else {
  59836. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59837. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59838. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59839. }
  59840. if (this.bloomEnabled) {
  59841. if (this._hdr) {
  59842. this.copyBack.shareOutputWith(this.blurX);
  59843. if (this.imageProcessing) {
  59844. this.imageProcessing.shareOutputWith(this.pass);
  59845. this.imageProcessing.autoClear = false;
  59846. }
  59847. else if (this.fxaa) {
  59848. this.fxaa.shareOutputWith(this.pass);
  59849. }
  59850. else {
  59851. this.finalMerge.shareOutputWith(this.pass);
  59852. }
  59853. }
  59854. else {
  59855. if (this.fxaa) {
  59856. this.fxaa.shareOutputWith(this.pass);
  59857. }
  59858. else {
  59859. this.finalMerge.shareOutputWith(this.pass);
  59860. }
  59861. }
  59862. }
  59863. if (this._cameras !== null) {
  59864. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59865. }
  59866. };
  59867. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59868. for (var i = 0; i < this._cameras.length; i++) {
  59869. var camera = this._cameras[i];
  59870. if (this.pass) {
  59871. this.pass.dispose(camera);
  59872. }
  59873. if (this.highlights) {
  59874. this.highlights.dispose(camera);
  59875. }
  59876. if (this.blurX) {
  59877. this.blurX.dispose(camera);
  59878. }
  59879. if (this.blurY) {
  59880. this.blurY.dispose(camera);
  59881. }
  59882. if (this.copyBack) {
  59883. this.copyBack.dispose(camera);
  59884. }
  59885. if (this.imageProcessing) {
  59886. this.imageProcessing.dispose(camera);
  59887. }
  59888. if (this.fxaa) {
  59889. this.fxaa.dispose(camera);
  59890. }
  59891. if (this.finalMerge) {
  59892. this.finalMerge.dispose(camera);
  59893. }
  59894. }
  59895. this.pass = null;
  59896. this.highlights = null;
  59897. this.blurX = null;
  59898. this.blurY = null;
  59899. this.copyBack = null;
  59900. this.imageProcessing = null;
  59901. this.fxaa = null;
  59902. this.finalMerge = null;
  59903. };
  59904. // Dispose
  59905. DefaultRenderingPipeline.prototype.dispose = function () {
  59906. this._disposePostProcesses();
  59907. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59908. _super.prototype.dispose.call(this);
  59909. };
  59910. // Serialize rendering pipeline
  59911. DefaultRenderingPipeline.prototype.serialize = function () {
  59912. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59913. serializationObject.customType = "DefaultRenderingPipeline";
  59914. return serializationObject;
  59915. };
  59916. // Parse serialized pipeline
  59917. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59918. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59919. };
  59920. __decorate([
  59921. BABYLON.serialize()
  59922. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59923. __decorate([
  59924. BABYLON.serialize()
  59925. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59926. __decorate([
  59927. BABYLON.serialize()
  59928. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59929. __decorate([
  59930. BABYLON.serialize()
  59931. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59932. __decorate([
  59933. BABYLON.serialize()
  59934. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59935. __decorate([
  59936. BABYLON.serialize()
  59937. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59938. __decorate([
  59939. BABYLON.serialize()
  59940. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59941. __decorate([
  59942. BABYLON.serialize()
  59943. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59944. return DefaultRenderingPipeline;
  59945. }(BABYLON.PostProcessRenderPipeline));
  59946. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59947. })(BABYLON || (BABYLON = {}));
  59948. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59949. var BABYLON;
  59950. (function (BABYLON) {
  59951. var GeometryBufferRenderer = /** @class */ (function () {
  59952. function GeometryBufferRenderer(scene, ratio) {
  59953. if (ratio === void 0) { ratio = 1; }
  59954. this._enablePosition = false;
  59955. this._scene = scene;
  59956. this._ratio = ratio;
  59957. // Render target
  59958. this._createRenderTargets();
  59959. }
  59960. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59961. set: function (meshes) {
  59962. this._multiRenderTarget.renderList = meshes;
  59963. },
  59964. enumerable: true,
  59965. configurable: true
  59966. });
  59967. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59968. get: function () {
  59969. return this._multiRenderTarget.isSupported;
  59970. },
  59971. enumerable: true,
  59972. configurable: true
  59973. });
  59974. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59975. get: function () {
  59976. return this._enablePosition;
  59977. },
  59978. set: function (enable) {
  59979. this._enablePosition = enable;
  59980. this.dispose();
  59981. this._createRenderTargets();
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59987. var material = subMesh.getMaterial();
  59988. if (material && material.disableDepthWrite) {
  59989. return false;
  59990. }
  59991. var defines = [];
  59992. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59993. var mesh = subMesh.getMesh();
  59994. // Alpha test
  59995. if (material && material.needAlphaTesting()) {
  59996. defines.push("#define ALPHATEST");
  59997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59998. attribs.push(BABYLON.VertexBuffer.UVKind);
  59999. defines.push("#define UV1");
  60000. }
  60001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60003. defines.push("#define UV2");
  60004. }
  60005. }
  60006. // Buffers
  60007. if (this._enablePosition) {
  60008. defines.push("#define POSITION");
  60009. }
  60010. // Bones
  60011. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60012. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60013. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60014. if (mesh.numBoneInfluencers > 4) {
  60015. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60016. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60017. }
  60018. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60019. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60020. }
  60021. else {
  60022. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60023. }
  60024. // Instances
  60025. if (useInstances) {
  60026. defines.push("#define INSTANCES");
  60027. attribs.push("world0");
  60028. attribs.push("world1");
  60029. attribs.push("world2");
  60030. attribs.push("world3");
  60031. }
  60032. // Get correct effect
  60033. var join = defines.join("\n");
  60034. if (this._cachedDefines !== join) {
  60035. this._cachedDefines = join;
  60036. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60037. }
  60038. return this._effect.isReady();
  60039. };
  60040. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60041. return this._multiRenderTarget;
  60042. };
  60043. // Methods
  60044. GeometryBufferRenderer.prototype.dispose = function () {
  60045. this.getGBuffer().dispose();
  60046. };
  60047. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60048. var _this = this;
  60049. var engine = this._scene.getEngine();
  60050. var count = this._enablePosition ? 3 : 2;
  60051. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60052. if (!this.isSupported) {
  60053. return;
  60054. }
  60055. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60056. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60057. this._multiRenderTarget.refreshRate = 1;
  60058. this._multiRenderTarget.renderParticles = false;
  60059. this._multiRenderTarget.renderList = null;
  60060. // set default depth value to 1.0 (far away)
  60061. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60062. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60063. });
  60064. // Custom render function
  60065. var renderSubMesh = function (subMesh) {
  60066. var mesh = subMesh.getRenderingMesh();
  60067. var scene = _this._scene;
  60068. var engine = scene.getEngine();
  60069. var material = subMesh.getMaterial();
  60070. if (!material) {
  60071. return;
  60072. }
  60073. // Culling
  60074. engine.setState(material.backFaceCulling);
  60075. // Managing instances
  60076. var batch = mesh._getInstancesRenderList(subMesh._id);
  60077. if (batch.mustReturn) {
  60078. return;
  60079. }
  60080. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60081. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60082. engine.enableEffect(_this._effect);
  60083. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60084. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60085. _this._effect.setMatrix("view", scene.getViewMatrix());
  60086. // Alpha test
  60087. if (material && material.needAlphaTesting()) {
  60088. var alphaTexture = material.getAlphaTestTexture();
  60089. if (alphaTexture) {
  60090. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60091. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60092. }
  60093. }
  60094. // Bones
  60095. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60096. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60097. }
  60098. // Draw
  60099. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60100. }
  60101. };
  60102. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60103. var index;
  60104. if (depthOnlySubMeshes.length) {
  60105. engine.setColorWrite(false);
  60106. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60107. renderSubMesh(depthOnlySubMeshes.data[index]);
  60108. }
  60109. engine.setColorWrite(true);
  60110. }
  60111. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60112. renderSubMesh(opaqueSubMeshes.data[index]);
  60113. }
  60114. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60115. renderSubMesh(alphaTestSubMeshes.data[index]);
  60116. }
  60117. };
  60118. };
  60119. return GeometryBufferRenderer;
  60120. }());
  60121. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60122. })(BABYLON || (BABYLON = {}));
  60123. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60124. var BABYLON;
  60125. (function (BABYLON) {
  60126. var RefractionPostProcess = /** @class */ (function (_super) {
  60127. __extends(RefractionPostProcess, _super);
  60128. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60129. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60130. _this.color = color;
  60131. _this.depth = depth;
  60132. _this.colorLevel = colorLevel;
  60133. _this.onActivateObservable.add(function (cam) {
  60134. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60135. });
  60136. _this.onApplyObservable.add(function (effect) {
  60137. effect.setColor3("baseColor", _this.color);
  60138. effect.setFloat("depth", _this.depth);
  60139. effect.setFloat("colorLevel", _this.colorLevel);
  60140. effect.setTexture("refractionSampler", _this._refRexture);
  60141. });
  60142. return _this;
  60143. }
  60144. // Methods
  60145. RefractionPostProcess.prototype.dispose = function (camera) {
  60146. if (this._refRexture) {
  60147. this._refRexture.dispose();
  60148. }
  60149. _super.prototype.dispose.call(this, camera);
  60150. };
  60151. return RefractionPostProcess;
  60152. }(BABYLON.PostProcess));
  60153. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60154. })(BABYLON || (BABYLON = {}));
  60155. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60156. var BABYLON;
  60157. (function (BABYLON) {
  60158. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60159. __extends(BlackAndWhitePostProcess, _super);
  60160. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60161. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60162. _this.degree = 1;
  60163. _this.onApplyObservable.add(function (effect) {
  60164. effect.setFloat("degree", _this.degree);
  60165. });
  60166. return _this;
  60167. }
  60168. return BlackAndWhitePostProcess;
  60169. }(BABYLON.PostProcess));
  60170. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60171. })(BABYLON || (BABYLON = {}));
  60172. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60173. var BABYLON;
  60174. (function (BABYLON) {
  60175. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60176. __extends(ConvolutionPostProcess, _super);
  60177. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60178. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60179. _this.kernel = kernel;
  60180. _this.onApply = function (effect) {
  60181. effect.setFloat2("screenSize", _this.width, _this.height);
  60182. effect.setArray("kernel", _this.kernel);
  60183. };
  60184. return _this;
  60185. }
  60186. // Statics
  60187. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60188. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60189. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60190. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60191. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60192. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60193. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60194. return ConvolutionPostProcess;
  60195. }(BABYLON.PostProcess));
  60196. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60197. })(BABYLON || (BABYLON = {}));
  60198. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60199. var BABYLON;
  60200. (function (BABYLON) {
  60201. var FilterPostProcess = /** @class */ (function (_super) {
  60202. __extends(FilterPostProcess, _super);
  60203. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60204. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60205. _this.kernelMatrix = kernelMatrix;
  60206. _this.onApply = function (effect) {
  60207. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60208. };
  60209. return _this;
  60210. }
  60211. return FilterPostProcess;
  60212. }(BABYLON.PostProcess));
  60213. BABYLON.FilterPostProcess = FilterPostProcess;
  60214. })(BABYLON || (BABYLON = {}));
  60215. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60216. var BABYLON;
  60217. (function (BABYLON) {
  60218. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60219. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60220. __extends(VolumetricLightScatteringPostProcess, _super);
  60221. /**
  60222. * @constructor
  60223. * @param {string} name - The post-process name
  60224. * @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)
  60225. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60226. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60227. * @param {number} samples - The post-process quality, default 100
  60228. * @param {number} samplingMode - The post-process filtering mode
  60229. * @param {BABYLON.Engine} engine - The babylon engine
  60230. * @param {boolean} reusable - If the post-process is reusable
  60231. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60232. */
  60233. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60234. if (samples === void 0) { samples = 100; }
  60235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60236. 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;
  60237. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60238. /**
  60239. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60240. * @type {Vector3}
  60241. */
  60242. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60243. /**
  60244. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60245. * @type {boolean}
  60246. */
  60247. _this.useCustomMeshPosition = false;
  60248. /**
  60249. * If the post-process should inverse the light scattering direction
  60250. * @type {boolean}
  60251. */
  60252. _this.invert = true;
  60253. /**
  60254. * Array containing the excluded meshes not rendered in the internal pass
  60255. */
  60256. _this.excludedMeshes = new Array();
  60257. /**
  60258. * Controls the overall intensity of the post-process
  60259. * @type {number}
  60260. */
  60261. _this.exposure = 0.3;
  60262. /**
  60263. * Dissipates each sample's contribution in range [0, 1]
  60264. * @type {number}
  60265. */
  60266. _this.decay = 0.96815;
  60267. /**
  60268. * Controls the overall intensity of each sample
  60269. * @type {number}
  60270. */
  60271. _this.weight = 0.58767;
  60272. /**
  60273. * Controls the density of each sample
  60274. * @type {number}
  60275. */
  60276. _this.density = 0.926;
  60277. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60278. engine = scene.getEngine();
  60279. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60280. // Configure mesh
  60281. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60282. // Configure
  60283. _this._createPass(scene, ratio.passRatio || ratio);
  60284. _this.onActivate = function (camera) {
  60285. if (!_this.isSupported) {
  60286. _this.dispose(camera);
  60287. }
  60288. _this.onActivate = null;
  60289. };
  60290. _this.onApplyObservable.add(function (effect) {
  60291. _this._updateMeshScreenCoordinates(scene);
  60292. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60293. effect.setFloat("exposure", _this.exposure);
  60294. effect.setFloat("decay", _this.decay);
  60295. effect.setFloat("weight", _this.weight);
  60296. effect.setFloat("density", _this.density);
  60297. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60298. });
  60299. return _this;
  60300. }
  60301. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60302. get: function () {
  60303. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60304. return false;
  60305. },
  60306. set: function (useDiffuseColor) {
  60307. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60308. },
  60309. enumerable: true,
  60310. configurable: true
  60311. });
  60312. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60313. return "VolumetricLightScatteringPostProcess";
  60314. };
  60315. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60316. var mesh = subMesh.getMesh();
  60317. // Render this.mesh as default
  60318. if (mesh === this.mesh && mesh.material) {
  60319. return mesh.material.isReady(mesh);
  60320. }
  60321. var defines = [];
  60322. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60323. var material = subMesh.getMaterial();
  60324. // Alpha test
  60325. if (material) {
  60326. if (material.needAlphaTesting()) {
  60327. defines.push("#define ALPHATEST");
  60328. }
  60329. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60330. attribs.push(BABYLON.VertexBuffer.UVKind);
  60331. defines.push("#define UV1");
  60332. }
  60333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60335. defines.push("#define UV2");
  60336. }
  60337. }
  60338. // Bones
  60339. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60342. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60343. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60344. }
  60345. else {
  60346. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60347. }
  60348. // Instances
  60349. if (useInstances) {
  60350. defines.push("#define INSTANCES");
  60351. attribs.push("world0");
  60352. attribs.push("world1");
  60353. attribs.push("world2");
  60354. attribs.push("world3");
  60355. }
  60356. // Get correct effect
  60357. var join = defines.join("\n");
  60358. if (this._cachedDefines !== join) {
  60359. this._cachedDefines = join;
  60360. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60361. }
  60362. return this._volumetricLightScatteringPass.isReady();
  60363. };
  60364. /**
  60365. * Sets the new light position for light scattering effect
  60366. * @param {BABYLON.Vector3} The new custom light position
  60367. */
  60368. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60369. this.customMeshPosition = position;
  60370. };
  60371. /**
  60372. * Returns the light position for light scattering effect
  60373. * @return {BABYLON.Vector3} The custom light position
  60374. */
  60375. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60376. return this.customMeshPosition;
  60377. };
  60378. /**
  60379. * Disposes the internal assets and detaches the post-process from the camera
  60380. */
  60381. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60382. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60383. if (rttIndex !== -1) {
  60384. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60385. }
  60386. this._volumetricLightScatteringRTT.dispose();
  60387. _super.prototype.dispose.call(this, camera);
  60388. };
  60389. /**
  60390. * Returns the render target texture used by the post-process
  60391. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60392. */
  60393. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60394. return this._volumetricLightScatteringRTT;
  60395. };
  60396. // Private methods
  60397. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60398. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60399. return true;
  60400. }
  60401. return false;
  60402. };
  60403. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60404. var _this = this;
  60405. var engine = scene.getEngine();
  60406. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60407. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60408. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60409. this._volumetricLightScatteringRTT.renderList = null;
  60410. this._volumetricLightScatteringRTT.renderParticles = false;
  60411. var camera = this.getCamera();
  60412. if (camera) {
  60413. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60414. }
  60415. else {
  60416. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60417. }
  60418. // Custom render function for submeshes
  60419. var renderSubMesh = function (subMesh) {
  60420. var mesh = subMesh.getRenderingMesh();
  60421. if (_this._meshExcluded(mesh)) {
  60422. return;
  60423. }
  60424. var material = subMesh.getMaterial();
  60425. if (!material) {
  60426. return;
  60427. }
  60428. var scene = mesh.getScene();
  60429. var engine = scene.getEngine();
  60430. // Culling
  60431. engine.setState(material.backFaceCulling);
  60432. // Managing instances
  60433. var batch = mesh._getInstancesRenderList(subMesh._id);
  60434. if (batch.mustReturn) {
  60435. return;
  60436. }
  60437. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60438. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60439. var effect = _this._volumetricLightScatteringPass;
  60440. if (mesh === _this.mesh) {
  60441. if (subMesh.effect) {
  60442. effect = subMesh.effect;
  60443. }
  60444. else {
  60445. effect = material.getEffect();
  60446. }
  60447. }
  60448. engine.enableEffect(effect);
  60449. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60450. if (mesh === _this.mesh) {
  60451. material.bind(mesh.getWorldMatrix(), mesh);
  60452. }
  60453. else {
  60454. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60455. // Alpha test
  60456. if (material && material.needAlphaTesting()) {
  60457. var alphaTexture = material.getAlphaTestTexture();
  60458. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60459. if (alphaTexture) {
  60460. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60461. }
  60462. }
  60463. // Bones
  60464. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60465. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60466. }
  60467. }
  60468. // Draw
  60469. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60470. }
  60471. };
  60472. // Render target texture callbacks
  60473. var savedSceneClearColor;
  60474. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60475. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60476. savedSceneClearColor = scene.clearColor;
  60477. scene.clearColor = sceneClearColor;
  60478. });
  60479. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60480. scene.clearColor = savedSceneClearColor;
  60481. });
  60482. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60483. var engine = scene.getEngine();
  60484. var index;
  60485. if (depthOnlySubMeshes.length) {
  60486. engine.setColorWrite(false);
  60487. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60488. renderSubMesh(depthOnlySubMeshes.data[index]);
  60489. }
  60490. engine.setColorWrite(true);
  60491. }
  60492. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60493. renderSubMesh(opaqueSubMeshes.data[index]);
  60494. }
  60495. engine.setAlphaTesting(true);
  60496. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60497. renderSubMesh(alphaTestSubMeshes.data[index]);
  60498. }
  60499. engine.setAlphaTesting(false);
  60500. if (transparentSubMeshes.length) {
  60501. // Sort sub meshes
  60502. for (index = 0; index < transparentSubMeshes.length; index++) {
  60503. var submesh = transparentSubMeshes.data[index];
  60504. var boundingInfo = submesh.getBoundingInfo();
  60505. if (boundingInfo && scene.activeCamera) {
  60506. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60507. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60508. }
  60509. }
  60510. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60511. sortedArray.sort(function (a, b) {
  60512. // Alpha index first
  60513. if (a._alphaIndex > b._alphaIndex) {
  60514. return 1;
  60515. }
  60516. if (a._alphaIndex < b._alphaIndex) {
  60517. return -1;
  60518. }
  60519. // Then distance to camera
  60520. if (a._distanceToCamera < b._distanceToCamera) {
  60521. return 1;
  60522. }
  60523. if (a._distanceToCamera > b._distanceToCamera) {
  60524. return -1;
  60525. }
  60526. return 0;
  60527. });
  60528. // Render sub meshes
  60529. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60530. for (index = 0; index < sortedArray.length; index++) {
  60531. renderSubMesh(sortedArray[index]);
  60532. }
  60533. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60534. }
  60535. };
  60536. };
  60537. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60538. var transform = scene.getTransformMatrix();
  60539. var meshPosition;
  60540. if (this.useCustomMeshPosition) {
  60541. meshPosition = this.customMeshPosition;
  60542. }
  60543. else if (this.attachedNode) {
  60544. meshPosition = this.attachedNode.position;
  60545. }
  60546. else {
  60547. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60548. }
  60549. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60550. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60551. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60552. if (this.invert)
  60553. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60554. };
  60555. // Static methods
  60556. /**
  60557. * Creates a default mesh for the Volumeric Light Scattering post-process
  60558. * @param {string} The mesh name
  60559. * @param {BABYLON.Scene} The scene where to create the mesh
  60560. * @return {BABYLON.Mesh} the default mesh
  60561. */
  60562. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60563. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60564. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60565. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60566. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60567. mesh.material = material;
  60568. return mesh;
  60569. };
  60570. __decorate([
  60571. BABYLON.serializeAsVector3()
  60572. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60573. __decorate([
  60574. BABYLON.serialize()
  60575. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60576. __decorate([
  60577. BABYLON.serialize()
  60578. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60579. __decorate([
  60580. BABYLON.serializeAsMeshReference()
  60581. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60582. __decorate([
  60583. BABYLON.serialize()
  60584. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60585. __decorate([
  60586. BABYLON.serialize()
  60587. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60588. __decorate([
  60589. BABYLON.serialize()
  60590. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60591. __decorate([
  60592. BABYLON.serialize()
  60593. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60594. __decorate([
  60595. BABYLON.serialize()
  60596. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60597. return VolumetricLightScatteringPostProcess;
  60598. }(BABYLON.PostProcess));
  60599. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60600. })(BABYLON || (BABYLON = {}));
  60601. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60602. //
  60603. // This post-process allows the modification of rendered colors by using
  60604. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60605. //
  60606. // The object needs to be provided an url to a texture containing the color
  60607. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60608. // Use an image editing software to tweak the LUT to match your needs.
  60609. //
  60610. // For an example of a color LUT, see here:
  60611. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60612. // For explanations on color grading, see here:
  60613. // http://udn.epicgames.com/Three/ColorGrading.html
  60614. //
  60615. var BABYLON;
  60616. (function (BABYLON) {
  60617. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60618. __extends(ColorCorrectionPostProcess, _super);
  60619. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60620. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60621. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60622. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60623. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60624. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60625. _this.onApply = function (effect) {
  60626. effect.setTexture("colorTable", _this._colorTableTexture);
  60627. };
  60628. return _this;
  60629. }
  60630. return ColorCorrectionPostProcess;
  60631. }(BABYLON.PostProcess));
  60632. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60633. })(BABYLON || (BABYLON = {}));
  60634. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60635. var BABYLON;
  60636. (function (BABYLON) {
  60637. var TonemappingOperator;
  60638. (function (TonemappingOperator) {
  60639. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60640. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60641. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60642. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60643. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60644. ;
  60645. var TonemapPostProcess = /** @class */ (function (_super) {
  60646. __extends(TonemapPostProcess, _super);
  60647. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60649. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60650. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60651. _this._operator = _operator;
  60652. _this.exposureAdjustment = exposureAdjustment;
  60653. var defines = "#define ";
  60654. if (_this._operator === TonemappingOperator.Hable)
  60655. defines += "HABLE_TONEMAPPING";
  60656. else if (_this._operator === TonemappingOperator.Reinhard)
  60657. defines += "REINHARD_TONEMAPPING";
  60658. else if (_this._operator === TonemappingOperator.HejiDawson)
  60659. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60660. else if (_this._operator === TonemappingOperator.Photographic)
  60661. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60662. //sadly a second call to create the effect.
  60663. _this.updateEffect(defines);
  60664. _this.onApply = function (effect) {
  60665. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60666. };
  60667. return _this;
  60668. }
  60669. return TonemapPostProcess;
  60670. }(BABYLON.PostProcess));
  60671. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60672. })(BABYLON || (BABYLON = {}));
  60673. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60674. var BABYLON;
  60675. (function (BABYLON) {
  60676. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60677. __extends(DisplayPassPostProcess, _super);
  60678. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60679. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60680. }
  60681. return DisplayPassPostProcess;
  60682. }(BABYLON.PostProcess));
  60683. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60684. })(BABYLON || (BABYLON = {}));
  60685. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60686. var BABYLON;
  60687. (function (BABYLON) {
  60688. var HighlightsPostProcess = /** @class */ (function (_super) {
  60689. __extends(HighlightsPostProcess, _super);
  60690. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60691. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60692. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60693. }
  60694. return HighlightsPostProcess;
  60695. }(BABYLON.PostProcess));
  60696. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60697. })(BABYLON || (BABYLON = {}));
  60698. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60699. var BABYLON;
  60700. (function (BABYLON) {
  60701. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60702. __extends(ImageProcessingPostProcess, _super);
  60703. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  60704. if (camera === void 0) { camera = null; }
  60705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60706. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60707. _this._fromLinearSpace = true;
  60708. /**
  60709. * Defines cache preventing GC.
  60710. */
  60711. _this._defines = {
  60712. IMAGEPROCESSING: false,
  60713. VIGNETTE: false,
  60714. VIGNETTEBLENDMODEMULTIPLY: false,
  60715. VIGNETTEBLENDMODEOPAQUE: false,
  60716. TONEMAPPING: false,
  60717. CONTRAST: false,
  60718. COLORCURVES: false,
  60719. COLORGRADING: false,
  60720. COLORGRADING3D: false,
  60721. FROMLINEARSPACE: false,
  60722. SAMPLER3DGREENDEPTH: false,
  60723. SAMPLER3DBGRMAP: false,
  60724. IMAGEPROCESSINGPOSTPROCESS: false,
  60725. EXPOSURE: false,
  60726. };
  60727. // Setup the configuration as forced by the constructor. This would then not force the
  60728. // scene materials output in linear space and let untouched the default forward pass.
  60729. if (imageProcessingConfiguration) {
  60730. imageProcessingConfiguration.applyByPostProcess = true;
  60731. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  60732. // This will cause the shader to be compiled
  60733. _this.fromLinearSpace = false;
  60734. }
  60735. else {
  60736. _this._attachImageProcessingConfiguration(null, true);
  60737. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60738. }
  60739. _this.onApply = function (effect) {
  60740. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60741. };
  60742. return _this;
  60743. }
  60744. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60745. /**
  60746. * Gets the image processing configuration used either in this material.
  60747. */
  60748. get: function () {
  60749. return this._imageProcessingConfiguration;
  60750. },
  60751. /**
  60752. * Sets the Default image processing configuration used either in the this material.
  60753. *
  60754. * If sets to null, the scene one is in use.
  60755. */
  60756. set: function (value) {
  60757. this._attachImageProcessingConfiguration(value);
  60758. },
  60759. enumerable: true,
  60760. configurable: true
  60761. });
  60762. /**
  60763. * Attaches a new image processing configuration to the PBR Material.
  60764. * @param configuration
  60765. */
  60766. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60767. var _this = this;
  60768. if (doNotBuild === void 0) { doNotBuild = false; }
  60769. if (configuration === this._imageProcessingConfiguration) {
  60770. return;
  60771. }
  60772. // Detaches observer.
  60773. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60774. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60775. }
  60776. // Pick the scene configuration if needed.
  60777. if (!configuration) {
  60778. var scene = null;
  60779. var engine = this.getEngine();
  60780. var camera = this.getCamera();
  60781. if (camera) {
  60782. scene = camera.getScene();
  60783. }
  60784. else if (engine && engine.scenes) {
  60785. var scenes = engine.scenes;
  60786. scene = scenes[scenes.length - 1];
  60787. }
  60788. else {
  60789. scene = BABYLON.Engine.LastCreatedScene;
  60790. }
  60791. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60792. }
  60793. else {
  60794. this._imageProcessingConfiguration = configuration;
  60795. }
  60796. // Attaches observer.
  60797. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60798. _this._updateParameters();
  60799. });
  60800. // Ensure the effect will be rebuilt.
  60801. if (!doNotBuild) {
  60802. this._updateParameters();
  60803. }
  60804. };
  60805. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60806. /**
  60807. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60808. */
  60809. get: function () {
  60810. return this.imageProcessingConfiguration.colorCurves;
  60811. },
  60812. /**
  60813. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60814. */
  60815. set: function (value) {
  60816. this.imageProcessingConfiguration.colorCurves = value;
  60817. },
  60818. enumerable: true,
  60819. configurable: true
  60820. });
  60821. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60822. /**
  60823. * Gets wether the color curves effect is enabled.
  60824. */
  60825. get: function () {
  60826. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60827. },
  60828. /**
  60829. * Sets wether the color curves effect is enabled.
  60830. */
  60831. set: function (value) {
  60832. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60833. },
  60834. enumerable: true,
  60835. configurable: true
  60836. });
  60837. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60838. /**
  60839. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60840. */
  60841. get: function () {
  60842. return this.imageProcessingConfiguration.colorGradingTexture;
  60843. },
  60844. /**
  60845. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60846. */
  60847. set: function (value) {
  60848. this.imageProcessingConfiguration.colorGradingTexture = value;
  60849. },
  60850. enumerable: true,
  60851. configurable: true
  60852. });
  60853. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60854. /**
  60855. * Gets wether the color grading effect is enabled.
  60856. */
  60857. get: function () {
  60858. return this.imageProcessingConfiguration.colorGradingEnabled;
  60859. },
  60860. /**
  60861. * Gets wether the color grading effect is enabled.
  60862. */
  60863. set: function (value) {
  60864. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60865. },
  60866. enumerable: true,
  60867. configurable: true
  60868. });
  60869. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60870. /**
  60871. * Gets exposure used in the effect.
  60872. */
  60873. get: function () {
  60874. return this.imageProcessingConfiguration.exposure;
  60875. },
  60876. /**
  60877. * Sets exposure used in the effect.
  60878. */
  60879. set: function (value) {
  60880. this.imageProcessingConfiguration.exposure = value;
  60881. },
  60882. enumerable: true,
  60883. configurable: true
  60884. });
  60885. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60886. /**
  60887. * Gets wether tonemapping is enabled or not.
  60888. */
  60889. get: function () {
  60890. return this._imageProcessingConfiguration.toneMappingEnabled;
  60891. },
  60892. /**
  60893. * Sets wether tonemapping is enabled or not
  60894. */
  60895. set: function (value) {
  60896. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60897. },
  60898. enumerable: true,
  60899. configurable: true
  60900. });
  60901. ;
  60902. ;
  60903. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60904. /**
  60905. * Gets contrast used in the effect.
  60906. */
  60907. get: function () {
  60908. return this.imageProcessingConfiguration.contrast;
  60909. },
  60910. /**
  60911. * Sets contrast used in the effect.
  60912. */
  60913. set: function (value) {
  60914. this.imageProcessingConfiguration.contrast = value;
  60915. },
  60916. enumerable: true,
  60917. configurable: true
  60918. });
  60919. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60920. /**
  60921. * Gets Vignette stretch size.
  60922. */
  60923. get: function () {
  60924. return this.imageProcessingConfiguration.vignetteStretch;
  60925. },
  60926. /**
  60927. * Sets Vignette stretch size.
  60928. */
  60929. set: function (value) {
  60930. this.imageProcessingConfiguration.vignetteStretch = value;
  60931. },
  60932. enumerable: true,
  60933. configurable: true
  60934. });
  60935. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60936. /**
  60937. * Gets Vignette centre X Offset.
  60938. */
  60939. get: function () {
  60940. return this.imageProcessingConfiguration.vignetteCentreX;
  60941. },
  60942. /**
  60943. * Sets Vignette centre X Offset.
  60944. */
  60945. set: function (value) {
  60946. this.imageProcessingConfiguration.vignetteCentreX = value;
  60947. },
  60948. enumerable: true,
  60949. configurable: true
  60950. });
  60951. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60952. /**
  60953. * Gets Vignette centre Y Offset.
  60954. */
  60955. get: function () {
  60956. return this.imageProcessingConfiguration.vignetteCentreY;
  60957. },
  60958. /**
  60959. * Sets Vignette centre Y Offset.
  60960. */
  60961. set: function (value) {
  60962. this.imageProcessingConfiguration.vignetteCentreY = value;
  60963. },
  60964. enumerable: true,
  60965. configurable: true
  60966. });
  60967. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60968. /**
  60969. * Gets Vignette weight or intensity of the vignette effect.
  60970. */
  60971. get: function () {
  60972. return this.imageProcessingConfiguration.vignetteWeight;
  60973. },
  60974. /**
  60975. * Sets Vignette weight or intensity of the vignette effect.
  60976. */
  60977. set: function (value) {
  60978. this.imageProcessingConfiguration.vignetteWeight = value;
  60979. },
  60980. enumerable: true,
  60981. configurable: true
  60982. });
  60983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60984. /**
  60985. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60986. * if vignetteEnabled is set to true.
  60987. */
  60988. get: function () {
  60989. return this.imageProcessingConfiguration.vignetteColor;
  60990. },
  60991. /**
  60992. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60993. * if vignetteEnabled is set to true.
  60994. */
  60995. set: function (value) {
  60996. this.imageProcessingConfiguration.vignetteColor = value;
  60997. },
  60998. enumerable: true,
  60999. configurable: true
  61000. });
  61001. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61002. /**
  61003. * Gets Camera field of view used by the Vignette effect.
  61004. */
  61005. get: function () {
  61006. return this.imageProcessingConfiguration.vignetteCameraFov;
  61007. },
  61008. /**
  61009. * Sets Camera field of view used by the Vignette effect.
  61010. */
  61011. set: function (value) {
  61012. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61013. },
  61014. enumerable: true,
  61015. configurable: true
  61016. });
  61017. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61018. /**
  61019. * Gets the vignette blend mode allowing different kind of effect.
  61020. */
  61021. get: function () {
  61022. return this.imageProcessingConfiguration.vignetteBlendMode;
  61023. },
  61024. /**
  61025. * Sets the vignette blend mode allowing different kind of effect.
  61026. */
  61027. set: function (value) {
  61028. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61029. },
  61030. enumerable: true,
  61031. configurable: true
  61032. });
  61033. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61034. /**
  61035. * Gets wether the vignette effect is enabled.
  61036. */
  61037. get: function () {
  61038. return this.imageProcessingConfiguration.vignetteEnabled;
  61039. },
  61040. /**
  61041. * Sets wether the vignette effect is enabled.
  61042. */
  61043. set: function (value) {
  61044. this.imageProcessingConfiguration.vignetteEnabled = value;
  61045. },
  61046. enumerable: true,
  61047. configurable: true
  61048. });
  61049. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61050. /**
  61051. * Gets wether the input of the processing is in Gamma or Linear Space.
  61052. */
  61053. get: function () {
  61054. return this._fromLinearSpace;
  61055. },
  61056. /**
  61057. * Sets wether the input of the processing is in Gamma or Linear Space.
  61058. */
  61059. set: function (value) {
  61060. if (this._fromLinearSpace === value) {
  61061. return;
  61062. }
  61063. this._fromLinearSpace = value;
  61064. this._updateParameters();
  61065. },
  61066. enumerable: true,
  61067. configurable: true
  61068. });
  61069. ImageProcessingPostProcess.prototype.getClassName = function () {
  61070. return "ImageProcessingPostProcess";
  61071. };
  61072. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61073. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61074. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61075. var defines = "";
  61076. for (var define in this._defines) {
  61077. if (this._defines[define]) {
  61078. defines += "#define " + define + ";\r\n";
  61079. }
  61080. }
  61081. var samplers = ["textureSampler"];
  61082. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61083. var uniforms = ["scale"];
  61084. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61085. this.updateEffect(defines, uniforms, samplers);
  61086. };
  61087. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61088. _super.prototype.dispose.call(this, camera);
  61089. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61090. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61091. }
  61092. this.imageProcessingConfiguration.applyByPostProcess = false;
  61093. };
  61094. __decorate([
  61095. BABYLON.serialize()
  61096. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61097. return ImageProcessingPostProcess;
  61098. }(BABYLON.PostProcess));
  61099. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61100. })(BABYLON || (BABYLON = {}));
  61101. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61102. var BABYLON;
  61103. (function (BABYLON) {
  61104. var BlurPostProcess = /** @class */ (function (_super) {
  61105. __extends(BlurPostProcess, _super);
  61106. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61109. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61110. _this.direction = direction;
  61111. _this._packedFloat = false;
  61112. _this.onApplyObservable.add(function (effect) {
  61113. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61114. });
  61115. _this.kernel = kernel;
  61116. return _this;
  61117. }
  61118. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61119. /**
  61120. * Gets the length in pixels of the blur sample region
  61121. */
  61122. get: function () {
  61123. return this._idealKernel;
  61124. },
  61125. /**
  61126. * Sets the length in pixels of the blur sample region
  61127. */
  61128. set: function (v) {
  61129. if (this._idealKernel === v) {
  61130. return;
  61131. }
  61132. v = Math.max(v, 1);
  61133. this._idealKernel = v;
  61134. this._kernel = this._nearestBestKernel(v);
  61135. this._updateParameters();
  61136. },
  61137. enumerable: true,
  61138. configurable: true
  61139. });
  61140. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61141. /**
  61142. * Gets wether or not the blur is unpacking/repacking floats
  61143. */
  61144. get: function () {
  61145. return this._packedFloat;
  61146. },
  61147. /**
  61148. * Sets wether or not the blur needs to unpack/repack floats
  61149. */
  61150. set: function (v) {
  61151. if (this._packedFloat === v) {
  61152. return;
  61153. }
  61154. this._packedFloat = v;
  61155. this._updateParameters();
  61156. },
  61157. enumerable: true,
  61158. configurable: true
  61159. });
  61160. BlurPostProcess.prototype._updateParameters = function () {
  61161. // Generate sampling offsets and weights
  61162. var N = this._kernel;
  61163. var centerIndex = (N - 1) / 2;
  61164. // Generate Gaussian sampling weights over kernel
  61165. var offsets = [];
  61166. var weights = [];
  61167. var totalWeight = 0;
  61168. for (var i = 0; i < N; i++) {
  61169. var u = i / (N - 1);
  61170. var w = this._gaussianWeight(u * 2.0 - 1);
  61171. offsets[i] = (i - centerIndex);
  61172. weights[i] = w;
  61173. totalWeight += w;
  61174. }
  61175. // Normalize weights
  61176. for (var i = 0; i < weights.length; i++) {
  61177. weights[i] /= totalWeight;
  61178. }
  61179. // Optimize: combine samples to take advantage of hardware linear sampling
  61180. // Walk from left to center, combining pairs (symmetrically)
  61181. var linearSamplingWeights = [];
  61182. var linearSamplingOffsets = [];
  61183. var linearSamplingMap = [];
  61184. for (var i = 0; i <= centerIndex; i += 2) {
  61185. var j = Math.min(i + 1, Math.floor(centerIndex));
  61186. var singleCenterSample = i === j;
  61187. if (singleCenterSample) {
  61188. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61189. }
  61190. else {
  61191. var sharedCell = j === centerIndex;
  61192. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61193. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61194. if (offsetLinear === 0) {
  61195. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61196. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61197. }
  61198. else {
  61199. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61200. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61201. }
  61202. }
  61203. }
  61204. for (var i = 0; i < linearSamplingMap.length; i++) {
  61205. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61206. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61207. }
  61208. // Replace with optimized
  61209. offsets = linearSamplingOffsets;
  61210. weights = linearSamplingWeights;
  61211. // Generate shaders
  61212. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61213. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61214. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61215. var defines = "";
  61216. for (var i = 0; i < varyingCount; i++) {
  61217. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61218. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61219. }
  61220. var depCount = 0;
  61221. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61222. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61223. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61224. depCount++;
  61225. }
  61226. if (this.packedFloat) {
  61227. defines += "#define PACKEDFLOAT 1";
  61228. }
  61229. this.updateEffect(defines, null, null, {
  61230. varyingCount: varyingCount,
  61231. depCount: depCount
  61232. });
  61233. };
  61234. /**
  61235. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61236. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61237. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61238. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61239. * The gaps between physical kernels are compensated for in the weighting of the samples
  61240. * @param idealKernel Ideal blur kernel.
  61241. * @return Nearest best kernel.
  61242. */
  61243. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61244. var v = Math.round(idealKernel);
  61245. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61246. var k = _a[_i];
  61247. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61248. return Math.max(k, 3);
  61249. }
  61250. }
  61251. return Math.max(v, 3);
  61252. };
  61253. /**
  61254. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61255. * @param x The point on the Gaussian distribution to sample.
  61256. * @return the value of the Gaussian function at x.
  61257. */
  61258. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61259. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61260. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61261. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61262. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61263. // truncated at around 1.3% of peak strength.
  61264. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61265. var sigma = (1 / 3);
  61266. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61267. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61268. var weight = (1.0 / denominator) * Math.exp(exponent);
  61269. return weight;
  61270. };
  61271. /**
  61272. * Generates a string that can be used as a floating point number in GLSL.
  61273. * @param x Value to print.
  61274. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61275. * @return GLSL float string.
  61276. */
  61277. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61278. if (decimalFigures === void 0) { decimalFigures = 8; }
  61279. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61280. };
  61281. return BlurPostProcess;
  61282. }(BABYLON.PostProcess));
  61283. BABYLON.BlurPostProcess = BlurPostProcess;
  61284. })(BABYLON || (BABYLON = {}));
  61285. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61286. var BABYLON;
  61287. (function (BABYLON) {
  61288. var Bone = /** @class */ (function (_super) {
  61289. __extends(Bone, _super);
  61290. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61291. if (parentBone === void 0) { parentBone = null; }
  61292. if (localMatrix === void 0) { localMatrix = null; }
  61293. if (restPose === void 0) { restPose = null; }
  61294. if (baseMatrix === void 0) { baseMatrix = null; }
  61295. if (index === void 0) { index = null; }
  61296. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61297. _this.name = name;
  61298. _this.children = new Array();
  61299. _this.animations = new Array();
  61300. // Set this value to map this bone to a different index in the transform matrices.
  61301. // Set this value to -1 to exclude the bone from the transform matrices.
  61302. _this._index = null;
  61303. _this._worldTransform = new BABYLON.Matrix();
  61304. _this._absoluteTransform = new BABYLON.Matrix();
  61305. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61306. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61307. _this._scaleVector = BABYLON.Vector3.One();
  61308. _this._negateScaleChildren = BABYLON.Vector3.One();
  61309. _this._scalingDeterminant = 1;
  61310. _this._skeleton = skeleton;
  61311. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61312. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61313. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61314. _this._index = index;
  61315. skeleton.bones.push(_this);
  61316. _this.setParent(parentBone, false);
  61317. _this._updateDifferenceMatrix();
  61318. return _this;
  61319. }
  61320. Object.defineProperty(Bone.prototype, "_matrix", {
  61321. get: function () {
  61322. return this._localMatrix;
  61323. },
  61324. set: function (val) {
  61325. if (this._localMatrix) {
  61326. this._localMatrix.copyFrom(val);
  61327. }
  61328. else {
  61329. this._localMatrix = val;
  61330. }
  61331. },
  61332. enumerable: true,
  61333. configurable: true
  61334. });
  61335. // Members
  61336. Bone.prototype.getSkeleton = function () {
  61337. return this._skeleton;
  61338. };
  61339. Bone.prototype.getParent = function () {
  61340. return this._parent;
  61341. };
  61342. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61343. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61344. if (this._parent === parent) {
  61345. return;
  61346. }
  61347. if (this._parent) {
  61348. var index = this._parent.children.indexOf(this);
  61349. if (index !== -1) {
  61350. this._parent.children.splice(index, 1);
  61351. }
  61352. }
  61353. this._parent = parent;
  61354. if (this._parent) {
  61355. this._parent.children.push(this);
  61356. }
  61357. if (updateDifferenceMatrix) {
  61358. this._updateDifferenceMatrix();
  61359. }
  61360. };
  61361. Bone.prototype.getLocalMatrix = function () {
  61362. return this._localMatrix;
  61363. };
  61364. Bone.prototype.getBaseMatrix = function () {
  61365. return this._baseMatrix;
  61366. };
  61367. Bone.prototype.getRestPose = function () {
  61368. return this._restPose;
  61369. };
  61370. Bone.prototype.returnToRest = function () {
  61371. this.updateMatrix(this._restPose.clone());
  61372. };
  61373. Bone.prototype.getWorldMatrix = function () {
  61374. return this._worldTransform;
  61375. };
  61376. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61377. return this._invertedAbsoluteTransform;
  61378. };
  61379. Bone.prototype.getAbsoluteTransform = function () {
  61380. return this._absoluteTransform;
  61381. };
  61382. Object.defineProperty(Bone.prototype, "position", {
  61383. // Properties (matches AbstractMesh properties)
  61384. get: function () {
  61385. return this.getPosition();
  61386. },
  61387. set: function (newPosition) {
  61388. this.setPosition(newPosition);
  61389. },
  61390. enumerable: true,
  61391. configurable: true
  61392. });
  61393. Object.defineProperty(Bone.prototype, "rotation", {
  61394. get: function () {
  61395. return this.getRotation();
  61396. },
  61397. set: function (newRotation) {
  61398. this.setRotation(newRotation);
  61399. },
  61400. enumerable: true,
  61401. configurable: true
  61402. });
  61403. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61404. get: function () {
  61405. return this.getRotationQuaternion();
  61406. },
  61407. set: function (newRotation) {
  61408. this.setRotationQuaternion(newRotation);
  61409. },
  61410. enumerable: true,
  61411. configurable: true
  61412. });
  61413. Object.defineProperty(Bone.prototype, "scaling", {
  61414. get: function () {
  61415. return this.getScale();
  61416. },
  61417. set: function (newScaling) {
  61418. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61419. },
  61420. enumerable: true,
  61421. configurable: true
  61422. });
  61423. // Methods
  61424. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61425. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61426. this._baseMatrix = matrix.clone();
  61427. this._localMatrix = matrix.clone();
  61428. this._skeleton._markAsDirty();
  61429. if (updateDifferenceMatrix) {
  61430. this._updateDifferenceMatrix();
  61431. }
  61432. };
  61433. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61434. if (!rootMatrix) {
  61435. rootMatrix = this._baseMatrix;
  61436. }
  61437. if (this._parent) {
  61438. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61439. }
  61440. else {
  61441. this._absoluteTransform.copyFrom(rootMatrix);
  61442. }
  61443. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61444. for (var index = 0; index < this.children.length; index++) {
  61445. this.children[index]._updateDifferenceMatrix();
  61446. }
  61447. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61448. };
  61449. Bone.prototype.markAsDirty = function () {
  61450. this._currentRenderId++;
  61451. this._skeleton._markAsDirty();
  61452. };
  61453. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61454. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61455. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61456. // all animation may be coming from a library skeleton, so may need to create animation
  61457. if (this.animations.length === 0) {
  61458. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61459. this.animations[0].setKeys([]);
  61460. }
  61461. // get animation info / verify there is such a range from the source bone
  61462. var sourceRange = source.animations[0].getRange(rangeName);
  61463. if (!sourceRange) {
  61464. return false;
  61465. }
  61466. var from = sourceRange.from;
  61467. var to = sourceRange.to;
  61468. var sourceKeys = source.animations[0].getKeys();
  61469. // rescaling prep
  61470. var sourceBoneLength = source.length;
  61471. var sourceParent = source.getParent();
  61472. var parent = this.getParent();
  61473. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61474. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61475. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61476. var destKeys = this.animations[0].getKeys();
  61477. // loop vars declaration
  61478. var orig;
  61479. var origTranslation;
  61480. var mat;
  61481. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61482. orig = sourceKeys[key];
  61483. if (orig.frame >= from && orig.frame <= to) {
  61484. if (rescaleAsRequired) {
  61485. mat = orig.value.clone();
  61486. // scale based on parent ratio, when bone has parent
  61487. if (parentScalingReqd) {
  61488. origTranslation = mat.getTranslation();
  61489. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61490. // scale based on skeleton dimension ratio when root bone, and value is passed
  61491. }
  61492. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61493. origTranslation = mat.getTranslation();
  61494. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61495. // use original when root bone, and no data for skelDimensionsRatio
  61496. }
  61497. else {
  61498. mat = orig.value;
  61499. }
  61500. }
  61501. else {
  61502. mat = orig.value;
  61503. }
  61504. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61505. }
  61506. }
  61507. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61508. return true;
  61509. };
  61510. /**
  61511. * Translate the bone in local or world space.
  61512. * @param vec The amount to translate the bone.
  61513. * @param space The space that the translation is in.
  61514. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61515. */
  61516. Bone.prototype.translate = function (vec, space, mesh) {
  61517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61518. var lm = this.getLocalMatrix();
  61519. if (space == BABYLON.Space.LOCAL) {
  61520. lm.m[12] += vec.x;
  61521. lm.m[13] += vec.y;
  61522. lm.m[14] += vec.z;
  61523. }
  61524. else {
  61525. var wm = null;
  61526. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61527. if (mesh) {
  61528. wm = mesh.getWorldMatrix();
  61529. }
  61530. this._skeleton.computeAbsoluteTransforms();
  61531. var tmat = Bone._tmpMats[0];
  61532. var tvec = Bone._tmpVecs[0];
  61533. if (this._parent) {
  61534. if (mesh && wm) {
  61535. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61536. tmat.multiplyToRef(wm, tmat);
  61537. }
  61538. else {
  61539. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61540. }
  61541. }
  61542. tmat.m[12] = 0;
  61543. tmat.m[13] = 0;
  61544. tmat.m[14] = 0;
  61545. tmat.invert();
  61546. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61547. lm.m[12] += tvec.x;
  61548. lm.m[13] += tvec.y;
  61549. lm.m[14] += tvec.z;
  61550. }
  61551. this.markAsDirty();
  61552. };
  61553. /**
  61554. * Set the postion of the bone in local or world space.
  61555. * @param position The position to set the bone.
  61556. * @param space The space that the position is in.
  61557. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61558. */
  61559. Bone.prototype.setPosition = function (position, space, mesh) {
  61560. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61561. var lm = this.getLocalMatrix();
  61562. if (space == BABYLON.Space.LOCAL) {
  61563. lm.m[12] = position.x;
  61564. lm.m[13] = position.y;
  61565. lm.m[14] = position.z;
  61566. }
  61567. else {
  61568. var wm = null;
  61569. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61570. if (mesh) {
  61571. wm = mesh.getWorldMatrix();
  61572. }
  61573. this._skeleton.computeAbsoluteTransforms();
  61574. var tmat = Bone._tmpMats[0];
  61575. var vec = Bone._tmpVecs[0];
  61576. if (this._parent) {
  61577. if (mesh && wm) {
  61578. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61579. tmat.multiplyToRef(wm, tmat);
  61580. }
  61581. else {
  61582. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61583. }
  61584. }
  61585. tmat.invert();
  61586. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61587. lm.m[12] = vec.x;
  61588. lm.m[13] = vec.y;
  61589. lm.m[14] = vec.z;
  61590. }
  61591. this.markAsDirty();
  61592. };
  61593. /**
  61594. * Set the absolute postion of the bone (world space).
  61595. * @param position The position to set the bone.
  61596. * @param mesh The mesh that this bone is attached to.
  61597. */
  61598. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61599. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61600. };
  61601. /**
  61602. * Set the scale of the bone on the x, y and z axes.
  61603. * @param x The scale of the bone on the x axis.
  61604. * @param x The scale of the bone on the y axis.
  61605. * @param z The scale of the bone on the z axis.
  61606. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61607. */
  61608. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61609. if (scaleChildren === void 0) { scaleChildren = false; }
  61610. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61611. if (!scaleChildren) {
  61612. this._negateScaleChildren.x = 1 / x;
  61613. this._negateScaleChildren.y = 1 / y;
  61614. this._negateScaleChildren.z = 1 / z;
  61615. }
  61616. this._syncScaleVector();
  61617. }
  61618. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61619. };
  61620. /**
  61621. * Scale the bone on the x, y and z axes.
  61622. * @param x The amount to scale the bone on the x axis.
  61623. * @param x The amount to scale the bone on the y axis.
  61624. * @param z The amount to scale the bone on the z axis.
  61625. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61626. */
  61627. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61628. if (scaleChildren === void 0) { scaleChildren = false; }
  61629. var locMat = this.getLocalMatrix();
  61630. var origLocMat = Bone._tmpMats[0];
  61631. origLocMat.copyFrom(locMat);
  61632. var origLocMatInv = Bone._tmpMats[1];
  61633. origLocMatInv.copyFrom(origLocMat);
  61634. origLocMatInv.invert();
  61635. var scaleMat = Bone._tmpMats[2];
  61636. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61637. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61638. this._scaleVector.x *= x;
  61639. this._scaleVector.y *= y;
  61640. this._scaleVector.z *= z;
  61641. locMat.multiplyToRef(origLocMatInv, locMat);
  61642. locMat.multiplyToRef(scaleMat, locMat);
  61643. locMat.multiplyToRef(origLocMat, locMat);
  61644. var parent = this.getParent();
  61645. if (parent) {
  61646. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61647. }
  61648. else {
  61649. this.getAbsoluteTransform().copyFrom(locMat);
  61650. }
  61651. var len = this.children.length;
  61652. scaleMat.invert();
  61653. for (var i = 0; i < len; i++) {
  61654. var child = this.children[i];
  61655. var cm = child.getLocalMatrix();
  61656. cm.multiplyToRef(scaleMat, cm);
  61657. var lm = child.getLocalMatrix();
  61658. lm.m[12] *= x;
  61659. lm.m[13] *= y;
  61660. lm.m[14] *= z;
  61661. }
  61662. this.computeAbsoluteTransforms();
  61663. if (scaleChildren) {
  61664. for (var i = 0; i < len; i++) {
  61665. this.children[i].scale(x, y, z, scaleChildren);
  61666. }
  61667. }
  61668. this.markAsDirty();
  61669. };
  61670. /**
  61671. * Set the yaw, pitch, and roll of the bone in local or world space.
  61672. * @param yaw The rotation of the bone on the y axis.
  61673. * @param pitch The rotation of the bone on the x axis.
  61674. * @param roll The rotation of the bone on the z axis.
  61675. * @param space The space that the axes of rotation are in.
  61676. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61677. */
  61678. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61680. var rotMat = Bone._tmpMats[0];
  61681. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61682. var rotMatInv = Bone._tmpMats[1];
  61683. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61684. rotMatInv.multiplyToRef(rotMat, rotMat);
  61685. this._rotateWithMatrix(rotMat, space, mesh);
  61686. };
  61687. /**
  61688. * Rotate the bone on an axis in local or world space.
  61689. * @param axis The axis to rotate the bone on.
  61690. * @param amount The amount to rotate the bone.
  61691. * @param space The space that the axis is in.
  61692. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61693. */
  61694. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61696. var rmat = Bone._tmpMats[0];
  61697. rmat.m[12] = 0;
  61698. rmat.m[13] = 0;
  61699. rmat.m[14] = 0;
  61700. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61701. this._rotateWithMatrix(rmat, space, mesh);
  61702. };
  61703. /**
  61704. * Set the rotation of the bone to a particular axis angle in local or world space.
  61705. * @param axis The axis to rotate the bone on.
  61706. * @param angle The angle that the bone should be rotated to.
  61707. * @param space The space that the axis is in.
  61708. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61709. */
  61710. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61712. var rotMat = Bone._tmpMats[0];
  61713. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61714. var rotMatInv = Bone._tmpMats[1];
  61715. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61716. rotMatInv.multiplyToRef(rotMat, rotMat);
  61717. this._rotateWithMatrix(rotMat, space, mesh);
  61718. };
  61719. /**
  61720. * Set the euler rotation of the bone in local of world space.
  61721. * @param rotation The euler rotation that the bone should be set to.
  61722. * @param space The space that the rotation is in.
  61723. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61724. */
  61725. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61726. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61727. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61728. };
  61729. /**
  61730. * Set the quaternion rotation of the bone in local of world space.
  61731. * @param quat The quaternion rotation that the bone should be set to.
  61732. * @param space The space that the rotation is in.
  61733. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61734. */
  61735. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61737. var rotMatInv = Bone._tmpMats[0];
  61738. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61739. var rotMat = Bone._tmpMats[1];
  61740. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61741. rotMatInv.multiplyToRef(rotMat, rotMat);
  61742. this._rotateWithMatrix(rotMat, space, mesh);
  61743. };
  61744. /**
  61745. * Set the rotation matrix of the bone in local of world space.
  61746. * @param rotMat The rotation matrix that the bone should be set to.
  61747. * @param space The space that the rotation is in.
  61748. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61749. */
  61750. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61752. var rotMatInv = Bone._tmpMats[0];
  61753. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61754. var rotMat2 = Bone._tmpMats[1];
  61755. rotMat2.copyFrom(rotMat);
  61756. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61757. this._rotateWithMatrix(rotMat2, space, mesh);
  61758. };
  61759. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61761. var lmat = this.getLocalMatrix();
  61762. var lx = lmat.m[12];
  61763. var ly = lmat.m[13];
  61764. var lz = lmat.m[14];
  61765. var parent = this.getParent();
  61766. var parentScale = Bone._tmpMats[3];
  61767. var parentScaleInv = Bone._tmpMats[4];
  61768. if (parent) {
  61769. if (space == BABYLON.Space.WORLD) {
  61770. if (mesh) {
  61771. parentScale.copyFrom(mesh.getWorldMatrix());
  61772. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61773. }
  61774. else {
  61775. parentScale.copyFrom(parent.getAbsoluteTransform());
  61776. }
  61777. }
  61778. else {
  61779. parentScale = parent._scaleMatrix;
  61780. }
  61781. parentScaleInv.copyFrom(parentScale);
  61782. parentScaleInv.invert();
  61783. lmat.multiplyToRef(parentScale, lmat);
  61784. lmat.multiplyToRef(rmat, lmat);
  61785. lmat.multiplyToRef(parentScaleInv, lmat);
  61786. }
  61787. else {
  61788. if (space == BABYLON.Space.WORLD && mesh) {
  61789. parentScale.copyFrom(mesh.getWorldMatrix());
  61790. parentScaleInv.copyFrom(parentScale);
  61791. parentScaleInv.invert();
  61792. lmat.multiplyToRef(parentScale, lmat);
  61793. lmat.multiplyToRef(rmat, lmat);
  61794. lmat.multiplyToRef(parentScaleInv, lmat);
  61795. }
  61796. else {
  61797. lmat.multiplyToRef(rmat, lmat);
  61798. }
  61799. }
  61800. lmat.m[12] = lx;
  61801. lmat.m[13] = ly;
  61802. lmat.m[14] = lz;
  61803. this.computeAbsoluteTransforms();
  61804. this.markAsDirty();
  61805. };
  61806. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61807. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61808. if (space == BABYLON.Space.WORLD) {
  61809. var scaleMatrix = Bone._tmpMats[2];
  61810. scaleMatrix.copyFrom(this._scaleMatrix);
  61811. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61812. if (mesh) {
  61813. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61814. var meshScale = Bone._tmpMats[3];
  61815. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61816. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61817. }
  61818. rotMatInv.invert();
  61819. scaleMatrix.m[0] *= this._scalingDeterminant;
  61820. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61821. }
  61822. else {
  61823. rotMatInv.copyFrom(this.getLocalMatrix());
  61824. rotMatInv.invert();
  61825. var scaleMatrix = Bone._tmpMats[2];
  61826. scaleMatrix.copyFrom(this._scaleMatrix);
  61827. if (this._parent) {
  61828. var pscaleMatrix = Bone._tmpMats[3];
  61829. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61830. pscaleMatrix.invert();
  61831. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61832. }
  61833. else {
  61834. scaleMatrix.m[0] *= this._scalingDeterminant;
  61835. }
  61836. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61837. }
  61838. };
  61839. /**
  61840. * Get the scale of the bone
  61841. * @returns the scale of the bone
  61842. */
  61843. Bone.prototype.getScale = function () {
  61844. return this._scaleVector.clone();
  61845. };
  61846. /**
  61847. * Copy the scale of the bone to a vector3.
  61848. * @param result The vector3 to copy the scale to
  61849. */
  61850. Bone.prototype.getScaleToRef = function (result) {
  61851. result.copyFrom(this._scaleVector);
  61852. };
  61853. /**
  61854. * Get the position of the bone in local or world space.
  61855. * @param space The space that the returned position is in.
  61856. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61857. * @returns The position of the bone
  61858. */
  61859. Bone.prototype.getPosition = function (space, mesh) {
  61860. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61861. if (mesh === void 0) { mesh = null; }
  61862. var pos = BABYLON.Vector3.Zero();
  61863. this.getPositionToRef(space, mesh, pos);
  61864. return pos;
  61865. };
  61866. /**
  61867. * Copy the position of the bone to a vector3 in local or world space.
  61868. * @param space The space that the returned position is in.
  61869. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61870. * @param result The vector3 to copy the position to.
  61871. */
  61872. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61873. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61874. if (space == BABYLON.Space.LOCAL) {
  61875. var lm = this.getLocalMatrix();
  61876. result.x = lm.m[12];
  61877. result.y = lm.m[13];
  61878. result.z = lm.m[14];
  61879. }
  61880. else {
  61881. var wm = null;
  61882. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61883. if (mesh) {
  61884. wm = mesh.getWorldMatrix();
  61885. }
  61886. this._skeleton.computeAbsoluteTransforms();
  61887. var tmat = Bone._tmpMats[0];
  61888. if (mesh && wm) {
  61889. tmat.copyFrom(this.getAbsoluteTransform());
  61890. tmat.multiplyToRef(wm, tmat);
  61891. }
  61892. else {
  61893. tmat = this.getAbsoluteTransform();
  61894. }
  61895. result.x = tmat.m[12];
  61896. result.y = tmat.m[13];
  61897. result.z = tmat.m[14];
  61898. }
  61899. };
  61900. /**
  61901. * Get the absolute position of the bone (world space).
  61902. * @param mesh The mesh that this bone is attached to.
  61903. * @returns The absolute position of the bone
  61904. */
  61905. Bone.prototype.getAbsolutePosition = function (mesh) {
  61906. if (mesh === void 0) { mesh = null; }
  61907. var pos = BABYLON.Vector3.Zero();
  61908. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61909. return pos;
  61910. };
  61911. /**
  61912. * Copy the absolute position of the bone (world space) to the result param.
  61913. * @param mesh The mesh that this bone is attached to.
  61914. * @param result The vector3 to copy the absolute position to.
  61915. */
  61916. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61917. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61918. };
  61919. /**
  61920. * Compute the absolute transforms of this bone and its children.
  61921. */
  61922. Bone.prototype.computeAbsoluteTransforms = function () {
  61923. if (this._parent) {
  61924. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61925. }
  61926. else {
  61927. this._absoluteTransform.copyFrom(this._localMatrix);
  61928. var poseMatrix = this._skeleton.getPoseMatrix();
  61929. if (poseMatrix) {
  61930. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61931. }
  61932. }
  61933. var children = this.children;
  61934. var len = children.length;
  61935. for (var i = 0; i < len; i++) {
  61936. children[i].computeAbsoluteTransforms();
  61937. }
  61938. };
  61939. Bone.prototype._syncScaleVector = function () {
  61940. var lm = this.getLocalMatrix();
  61941. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61942. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61943. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61944. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61945. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61946. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61947. this._scaleVector.x = xs * Math.sqrt(xsq);
  61948. this._scaleVector.y = ys * Math.sqrt(ysq);
  61949. this._scaleVector.z = zs * Math.sqrt(zsq);
  61950. if (this._parent) {
  61951. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61952. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61953. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61954. }
  61955. 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);
  61956. };
  61957. /**
  61958. * Get the world direction from an axis that is in the local space of the bone.
  61959. * @param localAxis The local direction that is used to compute the world direction.
  61960. * @param mesh The mesh that this bone is attached to.
  61961. * @returns The world direction
  61962. */
  61963. Bone.prototype.getDirection = function (localAxis, mesh) {
  61964. if (mesh === void 0) { mesh = null; }
  61965. var result = BABYLON.Vector3.Zero();
  61966. this.getDirectionToRef(localAxis, mesh, result);
  61967. return result;
  61968. };
  61969. /**
  61970. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61971. * @param localAxis The local direction that is used to compute the world direction.
  61972. * @param mesh The mesh that this bone is attached to.
  61973. * @param result The vector3 that the world direction will be copied to.
  61974. */
  61975. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61976. if (mesh === void 0) { mesh = null; }
  61977. var wm = null;
  61978. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61979. if (mesh) {
  61980. wm = mesh.getWorldMatrix();
  61981. }
  61982. this._skeleton.computeAbsoluteTransforms();
  61983. var mat = Bone._tmpMats[0];
  61984. mat.copyFrom(this.getAbsoluteTransform());
  61985. if (mesh && wm) {
  61986. mat.multiplyToRef(wm, mat);
  61987. }
  61988. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61989. result.normalize();
  61990. };
  61991. /**
  61992. * Get the euler rotation of the bone in local or world space.
  61993. * @param space The space that the rotation should be in.
  61994. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61995. * @returns The euler rotation
  61996. */
  61997. Bone.prototype.getRotation = function (space, mesh) {
  61998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61999. if (mesh === void 0) { mesh = null; }
  62000. var result = BABYLON.Vector3.Zero();
  62001. this.getRotationToRef(space, mesh, result);
  62002. return result;
  62003. };
  62004. /**
  62005. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62006. * @param space The space that the rotation should be in.
  62007. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62008. * @param result The vector3 that the rotation should be copied to.
  62009. */
  62010. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62012. if (mesh === void 0) { mesh = null; }
  62013. var quat = Bone._tmpQuat;
  62014. this.getRotationQuaternionToRef(space, mesh, quat);
  62015. quat.toEulerAnglesToRef(result);
  62016. };
  62017. /**
  62018. * Get the quaternion rotation of the bone in either local or world space.
  62019. * @param space The space that the rotation should be in.
  62020. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62021. * @returns The quaternion rotation
  62022. */
  62023. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62025. if (mesh === void 0) { mesh = null; }
  62026. var result = BABYLON.Quaternion.Identity();
  62027. this.getRotationQuaternionToRef(space, mesh, result);
  62028. return result;
  62029. };
  62030. /**
  62031. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62032. * @param space The space that the rotation should be in.
  62033. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62034. * @param result The quaternion that the rotation should be copied to.
  62035. */
  62036. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62038. if (mesh === void 0) { mesh = null; }
  62039. if (space == BABYLON.Space.LOCAL) {
  62040. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62041. }
  62042. else {
  62043. var mat = Bone._tmpMats[0];
  62044. var amat = this.getAbsoluteTransform();
  62045. if (mesh) {
  62046. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62047. }
  62048. else {
  62049. mat.copyFrom(amat);
  62050. }
  62051. mat.m[0] *= this._scalingDeterminant;
  62052. mat.m[1] *= this._scalingDeterminant;
  62053. mat.m[2] *= this._scalingDeterminant;
  62054. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62055. }
  62056. };
  62057. /**
  62058. * Get the rotation matrix of the bone in local or world space.
  62059. * @param space The space that the rotation should be in.
  62060. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62061. * @returns The rotation matrix
  62062. */
  62063. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62065. var result = BABYLON.Matrix.Identity();
  62066. this.getRotationMatrixToRef(space, mesh, result);
  62067. return result;
  62068. };
  62069. /**
  62070. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62071. * @param space The space that the rotation should be in.
  62072. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62073. * @param result The quaternion that the rotation should be copied to.
  62074. */
  62075. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62076. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62077. if (space == BABYLON.Space.LOCAL) {
  62078. this.getLocalMatrix().getRotationMatrixToRef(result);
  62079. }
  62080. else {
  62081. var mat = Bone._tmpMats[0];
  62082. var amat = this.getAbsoluteTransform();
  62083. if (mesh) {
  62084. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62085. }
  62086. else {
  62087. mat.copyFrom(amat);
  62088. }
  62089. mat.m[0] *= this._scalingDeterminant;
  62090. mat.m[1] *= this._scalingDeterminant;
  62091. mat.m[2] *= this._scalingDeterminant;
  62092. mat.getRotationMatrixToRef(result);
  62093. }
  62094. };
  62095. /**
  62096. * Get the world position of a point that is in the local space of the bone.
  62097. * @param position The local position
  62098. * @param mesh The mesh that this bone is attached to.
  62099. * @returns The world position
  62100. */
  62101. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62102. if (mesh === void 0) { mesh = null; }
  62103. var result = BABYLON.Vector3.Zero();
  62104. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62105. return result;
  62106. };
  62107. /**
  62108. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62109. * @param position The local position
  62110. * @param mesh The mesh that this bone is attached to.
  62111. * @param result The vector3 that the world position should be copied to.
  62112. */
  62113. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62114. if (mesh === void 0) { mesh = null; }
  62115. var wm = null;
  62116. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62117. if (mesh) {
  62118. wm = mesh.getWorldMatrix();
  62119. }
  62120. this._skeleton.computeAbsoluteTransforms();
  62121. var tmat = Bone._tmpMats[0];
  62122. if (mesh && wm) {
  62123. tmat.copyFrom(this.getAbsoluteTransform());
  62124. tmat.multiplyToRef(wm, tmat);
  62125. }
  62126. else {
  62127. tmat = this.getAbsoluteTransform();
  62128. }
  62129. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62130. };
  62131. /**
  62132. * Get the local position of a point that is in world space.
  62133. * @param position The world position
  62134. * @param mesh The mesh that this bone is attached to.
  62135. * @returns The local position
  62136. */
  62137. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62138. if (mesh === void 0) { mesh = null; }
  62139. var result = BABYLON.Vector3.Zero();
  62140. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62141. return result;
  62142. };
  62143. /**
  62144. * Get the local position of a point that is in world space and copy it to the result param.
  62145. * @param position The world position
  62146. * @param mesh The mesh that this bone is attached to.
  62147. * @param result The vector3 that the local position should be copied to.
  62148. */
  62149. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62150. if (mesh === void 0) { mesh = null; }
  62151. var wm = null;
  62152. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62153. if (mesh) {
  62154. wm = mesh.getWorldMatrix();
  62155. }
  62156. this._skeleton.computeAbsoluteTransforms();
  62157. var tmat = Bone._tmpMats[0];
  62158. tmat.copyFrom(this.getAbsoluteTransform());
  62159. if (mesh && wm) {
  62160. tmat.multiplyToRef(wm, tmat);
  62161. }
  62162. tmat.invert();
  62163. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62164. };
  62165. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62166. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62167. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62168. return Bone;
  62169. }(BABYLON.Node));
  62170. BABYLON.Bone = Bone;
  62171. })(BABYLON || (BABYLON = {}));
  62172. //# sourceMappingURL=babylon.bone.js.map
  62173. var BABYLON;
  62174. (function (BABYLON) {
  62175. var BoneIKController = /** @class */ (function () {
  62176. function BoneIKController(mesh, bone, options) {
  62177. this.targetPosition = BABYLON.Vector3.Zero();
  62178. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62179. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62180. this.poleAngle = 0;
  62181. this.slerpAmount = 1;
  62182. this._bone1Quat = BABYLON.Quaternion.Identity();
  62183. this._bone1Mat = BABYLON.Matrix.Identity();
  62184. this._bone2Ang = Math.PI;
  62185. this._maxAngle = Math.PI;
  62186. this._rightHandedSystem = false;
  62187. this._bendAxis = BABYLON.Vector3.Right();
  62188. this._slerping = false;
  62189. this._adjustRoll = 0;
  62190. this._bone2 = bone;
  62191. this._bone1 = bone.getParent();
  62192. if (!this._bone1) {
  62193. return;
  62194. }
  62195. this.mesh = mesh;
  62196. var bonePos = bone.getPosition();
  62197. if (bone.getAbsoluteTransform().determinant() > 0) {
  62198. this._rightHandedSystem = true;
  62199. this._bendAxis.x = 0;
  62200. this._bendAxis.y = 0;
  62201. this._bendAxis.z = -1;
  62202. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62203. this._adjustRoll = Math.PI * .5;
  62204. this._bendAxis.z = 1;
  62205. }
  62206. }
  62207. if (this._bone1.length) {
  62208. var boneScale1 = this._bone1.getScale();
  62209. var boneScale2 = this._bone2.getScale();
  62210. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62211. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62212. }
  62213. else if (this._bone1.children[0]) {
  62214. mesh.computeWorldMatrix(true);
  62215. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62216. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62217. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62218. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62219. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62220. }
  62221. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62222. this.maxAngle = Math.PI;
  62223. if (options) {
  62224. if (options.targetMesh) {
  62225. this.targetMesh = options.targetMesh;
  62226. this.targetMesh.computeWorldMatrix(true);
  62227. }
  62228. if (options.poleTargetMesh) {
  62229. this.poleTargetMesh = options.poleTargetMesh;
  62230. this.poleTargetMesh.computeWorldMatrix(true);
  62231. }
  62232. else if (options.poleTargetBone) {
  62233. this.poleTargetBone = options.poleTargetBone;
  62234. }
  62235. else if (this._bone1.getParent()) {
  62236. this.poleTargetBone = this._bone1.getParent();
  62237. }
  62238. if (options.poleTargetLocalOffset) {
  62239. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62240. }
  62241. if (options.poleAngle) {
  62242. this.poleAngle = options.poleAngle;
  62243. }
  62244. if (options.bendAxis) {
  62245. this._bendAxis.copyFrom(options.bendAxis);
  62246. }
  62247. if (options.maxAngle) {
  62248. this.maxAngle = options.maxAngle;
  62249. }
  62250. if (options.slerpAmount) {
  62251. this.slerpAmount = options.slerpAmount;
  62252. }
  62253. }
  62254. }
  62255. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62256. get: function () {
  62257. return this._maxAngle;
  62258. },
  62259. set: function (value) {
  62260. this._setMaxAngle(value);
  62261. },
  62262. enumerable: true,
  62263. configurable: true
  62264. });
  62265. BoneIKController.prototype._setMaxAngle = function (ang) {
  62266. if (ang < 0) {
  62267. ang = 0;
  62268. }
  62269. if (ang > Math.PI || ang == undefined) {
  62270. ang = Math.PI;
  62271. }
  62272. this._maxAngle = ang;
  62273. var a = this._bone1Length;
  62274. var b = this._bone2Length;
  62275. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62276. };
  62277. BoneIKController.prototype.update = function () {
  62278. var bone1 = this._bone1;
  62279. if (!bone1) {
  62280. return;
  62281. }
  62282. var target = this.targetPosition;
  62283. var poleTarget = this.poleTargetPosition;
  62284. var mat1 = BoneIKController._tmpMats[0];
  62285. var mat2 = BoneIKController._tmpMats[1];
  62286. if (this.targetMesh) {
  62287. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62288. }
  62289. if (this.poleTargetBone) {
  62290. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62291. }
  62292. else if (this.poleTargetMesh) {
  62293. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62294. }
  62295. var bonePos = BoneIKController._tmpVecs[0];
  62296. var zaxis = BoneIKController._tmpVecs[1];
  62297. var xaxis = BoneIKController._tmpVecs[2];
  62298. var yaxis = BoneIKController._tmpVecs[3];
  62299. var upAxis = BoneIKController._tmpVecs[4];
  62300. var _tmpQuat = BoneIKController._tmpQuat;
  62301. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62302. poleTarget.subtractToRef(bonePos, upAxis);
  62303. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62304. upAxis.y = 1;
  62305. }
  62306. else {
  62307. upAxis.normalize();
  62308. }
  62309. target.subtractToRef(bonePos, yaxis);
  62310. yaxis.normalize();
  62311. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62312. zaxis.normalize();
  62313. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62314. xaxis.normalize();
  62315. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62316. var a = this._bone1Length;
  62317. var b = this._bone2Length;
  62318. var c = BABYLON.Vector3.Distance(bonePos, target);
  62319. if (this._maxReach > 0) {
  62320. c = Math.min(this._maxReach, c);
  62321. }
  62322. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62323. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62324. if (acosa > 1) {
  62325. acosa = 1;
  62326. }
  62327. if (acosb > 1) {
  62328. acosb = 1;
  62329. }
  62330. if (acosa < -1) {
  62331. acosa = -1;
  62332. }
  62333. if (acosb < -1) {
  62334. acosb = -1;
  62335. }
  62336. var angA = Math.acos(acosa);
  62337. var angB = Math.acos(acosb);
  62338. var angC = -angA - angB;
  62339. if (this._rightHandedSystem) {
  62340. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62341. mat2.multiplyToRef(mat1, mat1);
  62342. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62343. mat2.multiplyToRef(mat1, mat1);
  62344. }
  62345. else {
  62346. var _tmpVec = BoneIKController._tmpVecs[5];
  62347. _tmpVec.copyFrom(this._bendAxis);
  62348. _tmpVec.x *= -1;
  62349. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62350. mat2.multiplyToRef(mat1, mat1);
  62351. }
  62352. if (this.poleAngle) {
  62353. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62354. mat1.multiplyToRef(mat2, mat1);
  62355. }
  62356. if (this._bone1) {
  62357. if (this.slerpAmount < 1) {
  62358. if (!this._slerping) {
  62359. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62360. }
  62361. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62362. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62363. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62364. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62365. this._slerping = true;
  62366. }
  62367. else {
  62368. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62369. this._bone1Mat.copyFrom(mat1);
  62370. this._slerping = false;
  62371. }
  62372. }
  62373. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62374. this._bone2Ang = angC;
  62375. };
  62376. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62377. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62378. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62379. return BoneIKController;
  62380. }());
  62381. BABYLON.BoneIKController = BoneIKController;
  62382. })(BABYLON || (BABYLON = {}));
  62383. //# sourceMappingURL=babylon.boneIKController.js.map
  62384. var BABYLON;
  62385. (function (BABYLON) {
  62386. var BoneLookController = /** @class */ (function () {
  62387. /**
  62388. * Create a BoneLookController
  62389. * @param mesh the mesh that the bone belongs to
  62390. * @param bone the bone that will be looking to the target
  62391. * @param target the target Vector3 to look at
  62392. * @param settings optional settings:
  62393. * - maxYaw: the maximum angle the bone will yaw to
  62394. * - minYaw: the minimum angle the bone will yaw to
  62395. * - maxPitch: the maximum angle the bone will pitch to
  62396. * - minPitch: the minimum angle the bone will yaw to
  62397. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62398. * - upAxis: the up axis of the coordinate system
  62399. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62400. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62401. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62402. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62403. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62404. * - adjustRoll: used to make an adjustment to the roll of the bone
  62405. **/
  62406. function BoneLookController(mesh, bone, target, options) {
  62407. /**
  62408. * The up axis of the coordinate system that is used when the bone is rotated.
  62409. */
  62410. this.upAxis = BABYLON.Vector3.Up();
  62411. /**
  62412. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62413. */
  62414. this.upAxisSpace = BABYLON.Space.LOCAL;
  62415. /**
  62416. * Used to make an adjustment to the yaw of the bone.
  62417. */
  62418. this.adjustYaw = 0;
  62419. /**
  62420. * Used to make an adjustment to the pitch of the bone.
  62421. */
  62422. this.adjustPitch = 0;
  62423. /**
  62424. * Used to make an adjustment to the roll of the bone.
  62425. */
  62426. this.adjustRoll = 0;
  62427. /**
  62428. * 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).
  62429. */
  62430. this.slerpAmount = 1;
  62431. this._boneQuat = BABYLON.Quaternion.Identity();
  62432. this._slerping = false;
  62433. this._firstFrameSkipped = false;
  62434. this._fowardAxis = BABYLON.Vector3.Forward();
  62435. this.mesh = mesh;
  62436. this.bone = bone;
  62437. this.target = target;
  62438. if (options) {
  62439. if (options.adjustYaw) {
  62440. this.adjustYaw = options.adjustYaw;
  62441. }
  62442. if (options.adjustPitch) {
  62443. this.adjustPitch = options.adjustPitch;
  62444. }
  62445. if (options.adjustRoll) {
  62446. this.adjustRoll = options.adjustRoll;
  62447. }
  62448. if (options.maxYaw != null) {
  62449. this.maxYaw = options.maxYaw;
  62450. }
  62451. else {
  62452. this.maxYaw = Math.PI;
  62453. }
  62454. if (options.minYaw != null) {
  62455. this.minYaw = options.minYaw;
  62456. }
  62457. else {
  62458. this.minYaw = -Math.PI;
  62459. }
  62460. if (options.maxPitch != null) {
  62461. this.maxPitch = options.maxPitch;
  62462. }
  62463. else {
  62464. this.maxPitch = Math.PI;
  62465. }
  62466. if (options.minPitch != null) {
  62467. this.minPitch = options.minPitch;
  62468. }
  62469. else {
  62470. this.minPitch = -Math.PI;
  62471. }
  62472. if (options.slerpAmount != null) {
  62473. this.slerpAmount = options.slerpAmount;
  62474. }
  62475. if (options.upAxis != null) {
  62476. this.upAxis = options.upAxis;
  62477. }
  62478. if (options.upAxisSpace != null) {
  62479. this.upAxisSpace = options.upAxisSpace;
  62480. }
  62481. if (options.yawAxis != null || options.pitchAxis != null) {
  62482. var newYawAxis = BABYLON.Axis.Y;
  62483. var newPitchAxis = BABYLON.Axis.X;
  62484. if (options.yawAxis != null) {
  62485. newYawAxis = options.yawAxis.clone();
  62486. newYawAxis.normalize();
  62487. }
  62488. if (options.pitchAxis != null) {
  62489. newPitchAxis = options.pitchAxis.clone();
  62490. newPitchAxis.normalize();
  62491. }
  62492. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62493. this._transformYawPitch = BABYLON.Matrix.Identity();
  62494. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62495. this._transformYawPitchInv = this._transformYawPitch.clone();
  62496. this._transformYawPitch.invert();
  62497. }
  62498. }
  62499. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62500. this.upAxisSpace = BABYLON.Space.LOCAL;
  62501. }
  62502. }
  62503. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62504. /**
  62505. * Get/set the minimum yaw angle that the bone can look to.
  62506. */
  62507. get: function () {
  62508. return this._minYaw;
  62509. },
  62510. set: function (value) {
  62511. this._minYaw = value;
  62512. this._minYawSin = Math.sin(value);
  62513. this._minYawCos = Math.cos(value);
  62514. if (this._maxYaw != null) {
  62515. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62516. this._yawRange = this._maxYaw - this._minYaw;
  62517. }
  62518. },
  62519. enumerable: true,
  62520. configurable: true
  62521. });
  62522. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62523. /**
  62524. * Get/set the maximum yaw angle that the bone can look to.
  62525. */
  62526. get: function () {
  62527. return this._maxYaw;
  62528. },
  62529. set: function (value) {
  62530. this._maxYaw = value;
  62531. this._maxYawSin = Math.sin(value);
  62532. this._maxYawCos = Math.cos(value);
  62533. if (this._minYaw != null) {
  62534. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62535. this._yawRange = this._maxYaw - this._minYaw;
  62536. }
  62537. },
  62538. enumerable: true,
  62539. configurable: true
  62540. });
  62541. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62542. /**
  62543. * Get/set the minimum pitch angle that the bone can look to.
  62544. */
  62545. get: function () {
  62546. return this._minPitch;
  62547. },
  62548. set: function (value) {
  62549. this._minPitch = value;
  62550. this._minPitchTan = Math.tan(value);
  62551. },
  62552. enumerable: true,
  62553. configurable: true
  62554. });
  62555. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62556. /**
  62557. * Get/set the maximum pitch angle that the bone can look to.
  62558. */
  62559. get: function () {
  62560. return this._maxPitch;
  62561. },
  62562. set: function (value) {
  62563. this._maxPitch = value;
  62564. this._maxPitchTan = Math.tan(value);
  62565. },
  62566. enumerable: true,
  62567. configurable: true
  62568. });
  62569. /**
  62570. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62571. */
  62572. BoneLookController.prototype.update = function () {
  62573. //skip the first frame when slerping so that the mesh rotation is correct
  62574. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62575. this._firstFrameSkipped = true;
  62576. return;
  62577. }
  62578. var bone = this.bone;
  62579. var bonePos = BoneLookController._tmpVecs[0];
  62580. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62581. var target = this.target;
  62582. var _tmpMat1 = BoneLookController._tmpMats[0];
  62583. var _tmpMat2 = BoneLookController._tmpMats[1];
  62584. var mesh = this.mesh;
  62585. var parentBone = bone.getParent();
  62586. var upAxis = BoneLookController._tmpVecs[1];
  62587. upAxis.copyFrom(this.upAxis);
  62588. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62589. if (this._transformYawPitch) {
  62590. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62591. }
  62592. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62593. }
  62594. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62595. mesh.getDirectionToRef(upAxis, upAxis);
  62596. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62597. upAxis.normalize();
  62598. }
  62599. }
  62600. var checkYaw = false;
  62601. var checkPitch = false;
  62602. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62603. checkYaw = true;
  62604. }
  62605. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62606. checkPitch = true;
  62607. }
  62608. if (checkYaw || checkPitch) {
  62609. var spaceMat = BoneLookController._tmpMats[2];
  62610. var spaceMatInv = BoneLookController._tmpMats[3];
  62611. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62612. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62613. }
  62614. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62615. spaceMat.copyFrom(mesh.getWorldMatrix());
  62616. }
  62617. else {
  62618. var forwardAxis = BoneLookController._tmpVecs[2];
  62619. forwardAxis.copyFrom(this._fowardAxis);
  62620. if (this._transformYawPitch) {
  62621. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62622. }
  62623. if (parentBone) {
  62624. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62625. }
  62626. else {
  62627. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62628. }
  62629. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62630. rightAxis.normalize();
  62631. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62632. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62633. }
  62634. spaceMat.invertToRef(spaceMatInv);
  62635. var xzlen = null;
  62636. if (checkPitch) {
  62637. var localTarget = BoneLookController._tmpVecs[3];
  62638. target.subtractToRef(bonePos, localTarget);
  62639. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62640. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62641. var pitch = Math.atan2(localTarget.y, xzlen);
  62642. var newPitch = pitch;
  62643. if (pitch > this._maxPitch) {
  62644. localTarget.y = this._maxPitchTan * xzlen;
  62645. newPitch = this._maxPitch;
  62646. }
  62647. else if (pitch < this._minPitch) {
  62648. localTarget.y = this._minPitchTan * xzlen;
  62649. newPitch = this._minPitch;
  62650. }
  62651. if (pitch != newPitch) {
  62652. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62653. localTarget.addInPlace(bonePos);
  62654. target = localTarget;
  62655. }
  62656. }
  62657. if (checkYaw) {
  62658. var localTarget = BoneLookController._tmpVecs[4];
  62659. target.subtractToRef(bonePos, localTarget);
  62660. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62661. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62662. var newYaw = yaw;
  62663. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62664. if (xzlen == null) {
  62665. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62666. }
  62667. if (this._yawRange > Math.PI) {
  62668. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62669. localTarget.z = this._maxYawCos * xzlen;
  62670. localTarget.x = this._maxYawSin * xzlen;
  62671. newYaw = this._maxYaw;
  62672. }
  62673. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62674. localTarget.z = this._minYawCos * xzlen;
  62675. localTarget.x = this._minYawSin * xzlen;
  62676. newYaw = this._minYaw;
  62677. }
  62678. }
  62679. else {
  62680. if (yaw > this._maxYaw) {
  62681. localTarget.z = this._maxYawCos * xzlen;
  62682. localTarget.x = this._maxYawSin * xzlen;
  62683. newYaw = this._maxYaw;
  62684. }
  62685. else if (yaw < this._minYaw) {
  62686. localTarget.z = this._minYawCos * xzlen;
  62687. localTarget.x = this._minYawSin * xzlen;
  62688. newYaw = this._minYaw;
  62689. }
  62690. }
  62691. }
  62692. if (this._slerping && this._yawRange > Math.PI) {
  62693. //are we going to be crossing into the min/max region?
  62694. var boneFwd = BoneLookController._tmpVecs[8];
  62695. boneFwd.copyFrom(BABYLON.Axis.Z);
  62696. if (this._transformYawPitch) {
  62697. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62698. }
  62699. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62700. this._boneQuat.toRotationMatrix(boneRotMat);
  62701. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62702. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62703. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62704. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62705. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62706. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62707. if (angBtwTar > angBtwMidYaw) {
  62708. if (xzlen == null) {
  62709. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62710. }
  62711. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62712. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62713. if (angBtwMin < angBtwMax) {
  62714. newYaw = boneYaw + Math.PI * .75;
  62715. localTarget.z = Math.cos(newYaw) * xzlen;
  62716. localTarget.x = Math.sin(newYaw) * xzlen;
  62717. }
  62718. else {
  62719. newYaw = boneYaw - Math.PI * .75;
  62720. localTarget.z = Math.cos(newYaw) * xzlen;
  62721. localTarget.x = Math.sin(newYaw) * xzlen;
  62722. }
  62723. }
  62724. }
  62725. if (yaw != newYaw) {
  62726. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62727. localTarget.addInPlace(bonePos);
  62728. target = localTarget;
  62729. }
  62730. }
  62731. }
  62732. var zaxis = BoneLookController._tmpVecs[5];
  62733. var xaxis = BoneLookController._tmpVecs[6];
  62734. var yaxis = BoneLookController._tmpVecs[7];
  62735. var _tmpQuat = BoneLookController._tmpQuat;
  62736. target.subtractToRef(bonePos, zaxis);
  62737. zaxis.normalize();
  62738. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62739. xaxis.normalize();
  62740. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62741. yaxis.normalize();
  62742. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62743. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62744. return;
  62745. }
  62746. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62747. return;
  62748. }
  62749. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62750. return;
  62751. }
  62752. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62753. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62754. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62755. }
  62756. if (this.slerpAmount < 1) {
  62757. if (!this._slerping) {
  62758. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62759. }
  62760. if (this._transformYawPitch) {
  62761. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62762. }
  62763. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62764. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62765. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62766. this._slerping = true;
  62767. }
  62768. else {
  62769. if (this._transformYawPitch) {
  62770. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62771. }
  62772. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62773. this._slerping = false;
  62774. }
  62775. };
  62776. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62777. var angDiff = ang2 - ang1;
  62778. angDiff %= Math.PI * 2;
  62779. if (angDiff > Math.PI) {
  62780. angDiff -= Math.PI * 2;
  62781. }
  62782. else if (angDiff < -Math.PI) {
  62783. angDiff += Math.PI * 2;
  62784. }
  62785. return angDiff;
  62786. };
  62787. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62788. ang1 %= (2 * Math.PI);
  62789. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62790. ang2 %= (2 * Math.PI);
  62791. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62792. var ab = 0;
  62793. if (ang1 < ang2) {
  62794. ab = ang2 - ang1;
  62795. }
  62796. else {
  62797. ab = ang1 - ang2;
  62798. }
  62799. if (ab > Math.PI) {
  62800. ab = Math.PI * 2 - ab;
  62801. }
  62802. return ab;
  62803. };
  62804. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62805. ang %= (2 * Math.PI);
  62806. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62807. ang1 %= (2 * Math.PI);
  62808. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62809. ang2 %= (2 * Math.PI);
  62810. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62811. if (ang1 < ang2) {
  62812. if (ang > ang1 && ang < ang2) {
  62813. return true;
  62814. }
  62815. }
  62816. else {
  62817. if (ang > ang2 && ang < ang1) {
  62818. return true;
  62819. }
  62820. }
  62821. return false;
  62822. };
  62823. 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()];
  62824. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62825. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62826. return BoneLookController;
  62827. }());
  62828. BABYLON.BoneLookController = BoneLookController;
  62829. })(BABYLON || (BABYLON = {}));
  62830. //# sourceMappingURL=babylon.boneLookController.js.map
  62831. var BABYLON;
  62832. (function (BABYLON) {
  62833. var Skeleton = /** @class */ (function () {
  62834. function Skeleton(name, id, scene) {
  62835. this.name = name;
  62836. this.id = id;
  62837. this.bones = new Array();
  62838. this.needInitialSkinMatrix = false;
  62839. this._isDirty = true;
  62840. this._meshesWithPoseMatrix = new Array();
  62841. this._identity = BABYLON.Matrix.Identity();
  62842. this._ranges = {};
  62843. this._lastAbsoluteTransformsUpdateId = -1;
  62844. // Events
  62845. /**
  62846. * An event triggered before computing the skeleton's matrices
  62847. * @type {BABYLON.Observable}
  62848. */
  62849. this.onBeforeComputeObservable = new BABYLON.Observable();
  62850. this.bones = [];
  62851. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62852. scene.skeletons.push(this);
  62853. //make sure it will recalculate the matrix next time prepare is called.
  62854. this._isDirty = true;
  62855. }
  62856. // Members
  62857. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62858. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62859. return mesh._bonesTransformMatrices;
  62860. }
  62861. if (!this._transformMatrices) {
  62862. this.prepare();
  62863. }
  62864. return this._transformMatrices;
  62865. };
  62866. Skeleton.prototype.getScene = function () {
  62867. return this._scene;
  62868. };
  62869. // Methods
  62870. /**
  62871. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62872. */
  62873. Skeleton.prototype.toString = function (fullDetails) {
  62874. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62875. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62876. if (fullDetails) {
  62877. ret += ", Ranges: {";
  62878. var first = true;
  62879. for (var name_1 in this._ranges) {
  62880. if (first) {
  62881. ret += ", ";
  62882. first = false;
  62883. }
  62884. ret += name_1;
  62885. }
  62886. ret += "}";
  62887. }
  62888. return ret;
  62889. };
  62890. /**
  62891. * Get bone's index searching by name
  62892. * @param {string} name is bone's name to search for
  62893. * @return {number} Indice of the bone. Returns -1 if not found
  62894. */
  62895. Skeleton.prototype.getBoneIndexByName = function (name) {
  62896. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62897. if (this.bones[boneIndex].name === name) {
  62898. return boneIndex;
  62899. }
  62900. }
  62901. return -1;
  62902. };
  62903. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62904. // check name not already in use
  62905. if (!this._ranges[name]) {
  62906. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62908. if (this.bones[i].animations[0]) {
  62909. this.bones[i].animations[0].createRange(name, from, to);
  62910. }
  62911. }
  62912. }
  62913. };
  62914. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62915. if (deleteFrames === void 0) { deleteFrames = true; }
  62916. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62917. if (this.bones[i].animations[0]) {
  62918. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62919. }
  62920. }
  62921. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62922. };
  62923. Skeleton.prototype.getAnimationRange = function (name) {
  62924. return this._ranges[name];
  62925. };
  62926. /**
  62927. * Returns as an Array, all AnimationRanges defined on this skeleton
  62928. */
  62929. Skeleton.prototype.getAnimationRanges = function () {
  62930. var animationRanges = [];
  62931. var name;
  62932. var i = 0;
  62933. for (name in this._ranges) {
  62934. animationRanges[i] = this._ranges[name];
  62935. i++;
  62936. }
  62937. return animationRanges;
  62938. };
  62939. /**
  62940. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62941. */
  62942. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62943. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62944. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62945. return false;
  62946. }
  62947. var ret = true;
  62948. var frameOffset = this._getHighestAnimationFrame() + 1;
  62949. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62950. var boneDict = {};
  62951. var sourceBones = source.bones;
  62952. var nBones;
  62953. var i;
  62954. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62955. boneDict[sourceBones[i].name] = sourceBones[i];
  62956. }
  62957. if (this.bones.length !== sourceBones.length) {
  62958. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62959. ret = false;
  62960. }
  62961. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62962. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62963. var boneName = this.bones[i].name;
  62964. var sourceBone = boneDict[boneName];
  62965. if (sourceBone) {
  62966. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62967. }
  62968. else {
  62969. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62970. ret = false;
  62971. }
  62972. }
  62973. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62974. var range = source.getAnimationRange(name);
  62975. if (range) {
  62976. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62977. }
  62978. return ret;
  62979. };
  62980. Skeleton.prototype.returnToRest = function () {
  62981. for (var index = 0; index < this.bones.length; index++) {
  62982. this.bones[index].returnToRest();
  62983. }
  62984. };
  62985. Skeleton.prototype._getHighestAnimationFrame = function () {
  62986. var ret = 0;
  62987. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62988. if (this.bones[i].animations[0]) {
  62989. var highest = this.bones[i].animations[0].getHighestFrame();
  62990. if (ret < highest) {
  62991. ret = highest;
  62992. }
  62993. }
  62994. }
  62995. return ret;
  62996. };
  62997. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62998. var range = this.getAnimationRange(name);
  62999. if (!range) {
  63000. return null;
  63001. }
  63002. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63003. };
  63004. Skeleton.prototype._markAsDirty = function () {
  63005. this._isDirty = true;
  63006. };
  63007. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63008. this._meshesWithPoseMatrix.push(mesh);
  63009. };
  63010. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63011. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63012. if (index > -1) {
  63013. this._meshesWithPoseMatrix.splice(index, 1);
  63014. }
  63015. };
  63016. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63017. this.onBeforeComputeObservable.notifyObservers(this);
  63018. for (var index = 0; index < this.bones.length; index++) {
  63019. var bone = this.bones[index];
  63020. var parentBone = bone.getParent();
  63021. if (parentBone) {
  63022. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63023. }
  63024. else {
  63025. if (initialSkinMatrix) {
  63026. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63027. }
  63028. else {
  63029. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63030. }
  63031. }
  63032. if (bone._index !== -1) {
  63033. var mappedIndex = bone._index === null ? index : bone._index;
  63034. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63035. }
  63036. }
  63037. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63038. };
  63039. Skeleton.prototype.prepare = function () {
  63040. if (!this._isDirty) {
  63041. return;
  63042. }
  63043. if (this.needInitialSkinMatrix) {
  63044. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63045. var mesh = this._meshesWithPoseMatrix[index];
  63046. var poseMatrix = mesh.getPoseMatrix();
  63047. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63048. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63049. }
  63050. if (this._synchronizedWithMesh !== mesh) {
  63051. this._synchronizedWithMesh = mesh;
  63052. // Prepare bones
  63053. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63054. var bone = this.bones[boneIndex];
  63055. if (!bone.getParent()) {
  63056. var matrix = bone.getBaseMatrix();
  63057. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63058. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63059. }
  63060. }
  63061. }
  63062. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63063. }
  63064. }
  63065. else {
  63066. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63067. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63068. }
  63069. this._computeTransformMatrices(this._transformMatrices, null);
  63070. }
  63071. this._isDirty = false;
  63072. this._scene._activeBones.addCount(this.bones.length, false);
  63073. };
  63074. Skeleton.prototype.getAnimatables = function () {
  63075. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63076. this._animatables = [];
  63077. for (var index = 0; index < this.bones.length; index++) {
  63078. this._animatables.push(this.bones[index]);
  63079. }
  63080. }
  63081. return this._animatables;
  63082. };
  63083. Skeleton.prototype.clone = function (name, id) {
  63084. var result = new Skeleton(name, id || name, this._scene);
  63085. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63086. for (var index = 0; index < this.bones.length; index++) {
  63087. var source = this.bones[index];
  63088. var parentBone = null;
  63089. var parent_1 = source.getParent();
  63090. if (parent_1) {
  63091. var parentIndex = this.bones.indexOf(parent_1);
  63092. parentBone = result.bones[parentIndex];
  63093. }
  63094. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63095. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63096. }
  63097. if (this._ranges) {
  63098. result._ranges = {};
  63099. for (var rangeName in this._ranges) {
  63100. var range = this._ranges[rangeName];
  63101. if (range) {
  63102. result._ranges[rangeName] = range.clone();
  63103. }
  63104. }
  63105. }
  63106. this._isDirty = true;
  63107. return result;
  63108. };
  63109. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63110. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63111. this.bones.forEach(function (bone) {
  63112. bone.animations.forEach(function (animation) {
  63113. animation.enableBlending = true;
  63114. animation.blendingSpeed = blendingSpeed;
  63115. });
  63116. });
  63117. };
  63118. Skeleton.prototype.dispose = function () {
  63119. this._meshesWithPoseMatrix = [];
  63120. // Animations
  63121. this.getScene().stopAnimation(this);
  63122. // Remove from scene
  63123. this.getScene().removeSkeleton(this);
  63124. };
  63125. Skeleton.prototype.serialize = function () {
  63126. var serializationObject = {};
  63127. serializationObject.name = this.name;
  63128. serializationObject.id = this.id;
  63129. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63130. serializationObject.bones = [];
  63131. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63132. for (var index = 0; index < this.bones.length; index++) {
  63133. var bone = this.bones[index];
  63134. var parent_2 = bone.getParent();
  63135. var serializedBone = {
  63136. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63137. name: bone.name,
  63138. matrix: bone.getBaseMatrix().toArray(),
  63139. rest: bone.getRestPose().toArray()
  63140. };
  63141. serializationObject.bones.push(serializedBone);
  63142. if (bone.length) {
  63143. serializedBone.length = bone.length;
  63144. }
  63145. if (bone.animations && bone.animations.length > 0) {
  63146. serializedBone.animation = bone.animations[0].serialize();
  63147. }
  63148. serializationObject.ranges = [];
  63149. for (var name in this._ranges) {
  63150. var source = this._ranges[name];
  63151. if (!source) {
  63152. continue;
  63153. }
  63154. var range = {};
  63155. range.name = name;
  63156. range.from = source.from;
  63157. range.to = source.to;
  63158. serializationObject.ranges.push(range);
  63159. }
  63160. }
  63161. return serializationObject;
  63162. };
  63163. Skeleton.Parse = function (parsedSkeleton, scene) {
  63164. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63165. if (parsedSkeleton.dimensionsAtRest) {
  63166. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63167. }
  63168. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63169. var index;
  63170. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63171. var parsedBone = parsedSkeleton.bones[index];
  63172. var parentBone = null;
  63173. if (parsedBone.parentBoneIndex > -1) {
  63174. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63175. }
  63176. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63177. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63178. if (parsedBone.length) {
  63179. bone.length = parsedBone.length;
  63180. }
  63181. if (parsedBone.animation) {
  63182. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63183. }
  63184. }
  63185. // placed after bones, so createAnimationRange can cascade down
  63186. if (parsedSkeleton.ranges) {
  63187. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63188. var data = parsedSkeleton.ranges[index];
  63189. skeleton.createAnimationRange(data.name, data.from, data.to);
  63190. }
  63191. }
  63192. return skeleton;
  63193. };
  63194. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63195. if (forceUpdate === void 0) { forceUpdate = false; }
  63196. var renderId = this._scene.getRenderId();
  63197. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63198. this.bones[0].computeAbsoluteTransforms();
  63199. this._lastAbsoluteTransformsUpdateId = renderId;
  63200. }
  63201. };
  63202. Skeleton.prototype.getPoseMatrix = function () {
  63203. var poseMatrix = null;
  63204. if (this._meshesWithPoseMatrix.length > 0) {
  63205. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63206. }
  63207. return poseMatrix;
  63208. };
  63209. Skeleton.prototype.sortBones = function () {
  63210. var bones = new Array();
  63211. var visited = new Array(this.bones.length);
  63212. for (var index = 0; index < this.bones.length; index++) {
  63213. this._sortBones(index, bones, visited);
  63214. }
  63215. this.bones = bones;
  63216. };
  63217. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63218. if (visited[index]) {
  63219. return;
  63220. }
  63221. visited[index] = true;
  63222. var bone = this.bones[index];
  63223. if (bone._index === undefined) {
  63224. bone._index = index;
  63225. }
  63226. var parentBone = bone.getParent();
  63227. if (parentBone) {
  63228. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63229. }
  63230. bones.push(bone);
  63231. };
  63232. return Skeleton;
  63233. }());
  63234. BABYLON.Skeleton = Skeleton;
  63235. })(BABYLON || (BABYLON = {}));
  63236. //# sourceMappingURL=babylon.skeleton.js.map
  63237. var BABYLON;
  63238. (function (BABYLON) {
  63239. var SphericalPolynomial = /** @class */ (function () {
  63240. function SphericalPolynomial() {
  63241. this.x = BABYLON.Vector3.Zero();
  63242. this.y = BABYLON.Vector3.Zero();
  63243. this.z = BABYLON.Vector3.Zero();
  63244. this.xx = BABYLON.Vector3.Zero();
  63245. this.yy = BABYLON.Vector3.Zero();
  63246. this.zz = BABYLON.Vector3.Zero();
  63247. this.xy = BABYLON.Vector3.Zero();
  63248. this.yz = BABYLON.Vector3.Zero();
  63249. this.zx = BABYLON.Vector3.Zero();
  63250. }
  63251. SphericalPolynomial.prototype.addAmbient = function (color) {
  63252. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63253. this.xx = this.xx.add(colorVector);
  63254. this.yy = this.yy.add(colorVector);
  63255. this.zz = this.zz.add(colorVector);
  63256. };
  63257. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63258. var result = new SphericalPolynomial();
  63259. result.x = harmonics.L11.scale(1.02333);
  63260. result.y = harmonics.L1_1.scale(1.02333);
  63261. result.z = harmonics.L10.scale(1.02333);
  63262. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63263. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63264. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63265. result.yz = harmonics.L2_1.scale(0.858086);
  63266. result.zx = harmonics.L21.scale(0.858086);
  63267. result.xy = harmonics.L2_2.scale(0.858086);
  63268. result.scale(1.0 / Math.PI);
  63269. return result;
  63270. };
  63271. SphericalPolynomial.prototype.scale = function (scale) {
  63272. this.x = this.x.scale(scale);
  63273. this.y = this.y.scale(scale);
  63274. this.z = this.z.scale(scale);
  63275. this.xx = this.xx.scale(scale);
  63276. this.yy = this.yy.scale(scale);
  63277. this.zz = this.zz.scale(scale);
  63278. this.yz = this.yz.scale(scale);
  63279. this.zx = this.zx.scale(scale);
  63280. this.xy = this.xy.scale(scale);
  63281. };
  63282. return SphericalPolynomial;
  63283. }());
  63284. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63285. var SphericalHarmonics = /** @class */ (function () {
  63286. function SphericalHarmonics() {
  63287. this.L00 = BABYLON.Vector3.Zero();
  63288. this.L1_1 = BABYLON.Vector3.Zero();
  63289. this.L10 = BABYLON.Vector3.Zero();
  63290. this.L11 = BABYLON.Vector3.Zero();
  63291. this.L2_2 = BABYLON.Vector3.Zero();
  63292. this.L2_1 = BABYLON.Vector3.Zero();
  63293. this.L20 = BABYLON.Vector3.Zero();
  63294. this.L21 = BABYLON.Vector3.Zero();
  63295. this.L22 = BABYLON.Vector3.Zero();
  63296. }
  63297. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63298. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63299. var c = colorVector.scale(deltaSolidAngle);
  63300. this.L00 = this.L00.add(c.scale(0.282095));
  63301. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63302. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63303. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63304. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63305. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63306. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63307. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63308. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63309. };
  63310. SphericalHarmonics.prototype.scale = function (scale) {
  63311. this.L00 = this.L00.scale(scale);
  63312. this.L1_1 = this.L1_1.scale(scale);
  63313. this.L10 = this.L10.scale(scale);
  63314. this.L11 = this.L11.scale(scale);
  63315. this.L2_2 = this.L2_2.scale(scale);
  63316. this.L2_1 = this.L2_1.scale(scale);
  63317. this.L20 = this.L20.scale(scale);
  63318. this.L21 = this.L21.scale(scale);
  63319. this.L22 = this.L22.scale(scale);
  63320. };
  63321. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63322. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63323. //
  63324. // E_lm = A_l * L_lm
  63325. //
  63326. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63327. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63328. // the scaling factors are given in equation 9.
  63329. // Constant (Band 0)
  63330. this.L00 = this.L00.scale(3.141593);
  63331. // Linear (Band 1)
  63332. this.L1_1 = this.L1_1.scale(2.094395);
  63333. this.L10 = this.L10.scale(2.094395);
  63334. this.L11 = this.L11.scale(2.094395);
  63335. // Quadratic (Band 2)
  63336. this.L2_2 = this.L2_2.scale(0.785398);
  63337. this.L2_1 = this.L2_1.scale(0.785398);
  63338. this.L20 = this.L20.scale(0.785398);
  63339. this.L21 = this.L21.scale(0.785398);
  63340. this.L22 = this.L22.scale(0.785398);
  63341. };
  63342. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63343. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63344. // L = (1/pi) * E * rho
  63345. //
  63346. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63347. this.scale(1.0 / Math.PI);
  63348. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63349. // (The pixel shader must apply albedo after texture fetches, etc).
  63350. };
  63351. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63352. var result = new SphericalHarmonics();
  63353. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63354. result.L1_1 = polynomial.y.scale(0.977204);
  63355. result.L10 = polynomial.z.scale(0.977204);
  63356. result.L11 = polynomial.x.scale(0.977204);
  63357. result.L2_2 = polynomial.xy.scale(1.16538);
  63358. result.L2_1 = polynomial.yz.scale(1.16538);
  63359. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63360. result.L21 = polynomial.zx.scale(1.16538);
  63361. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63362. result.scale(Math.PI);
  63363. return result;
  63364. };
  63365. return SphericalHarmonics;
  63366. }());
  63367. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63368. })(BABYLON || (BABYLON = {}));
  63369. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63370. var BABYLON;
  63371. (function (BABYLON) {
  63372. var Internals;
  63373. (function (Internals) {
  63374. var FileFaceOrientation = /** @class */ (function () {
  63375. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63376. this.name = name;
  63377. this.worldAxisForNormal = worldAxisForNormal;
  63378. this.worldAxisForFileX = worldAxisForFileX;
  63379. this.worldAxisForFileY = worldAxisForFileY;
  63380. }
  63381. return FileFaceOrientation;
  63382. }());
  63383. ;
  63384. /**
  63385. * Helper class dealing with the extraction of spherical polynomial dataArray
  63386. * from a cube map.
  63387. */
  63388. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63389. function CubeMapToSphericalPolynomialTools() {
  63390. }
  63391. /**
  63392. * Converts a texture to the according Spherical Polynomial data.
  63393. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63394. *
  63395. * @param texture The texture to extract the information from.
  63396. * @return The Spherical Polynomial data.
  63397. */
  63398. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63399. if (!texture.isCube) {
  63400. // Only supports cube Textures currently.
  63401. return null;
  63402. }
  63403. var size = texture.getSize().width;
  63404. var right = texture.readPixels(0);
  63405. var left = texture.readPixels(1);
  63406. var up;
  63407. var down;
  63408. if (texture.isRenderTarget) {
  63409. up = texture.readPixels(3);
  63410. down = texture.readPixels(2);
  63411. }
  63412. else {
  63413. up = texture.readPixels(2);
  63414. down = texture.readPixels(3);
  63415. }
  63416. var front = texture.readPixels(4);
  63417. var back = texture.readPixels(5);
  63418. var gammaSpace = texture.gammaSpace;
  63419. // Always read as RGBA.
  63420. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63421. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63422. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63423. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63424. }
  63425. var cubeInfo = {
  63426. size: size,
  63427. right: right,
  63428. left: left,
  63429. up: up,
  63430. down: down,
  63431. front: front,
  63432. back: back,
  63433. format: format,
  63434. type: type,
  63435. gammaSpace: gammaSpace,
  63436. };
  63437. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63438. };
  63439. /**
  63440. * Converts a cubemap to the according Spherical Polynomial data.
  63441. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63442. *
  63443. * @param cubeInfo The Cube map to extract the information from.
  63444. * @return The Spherical Polynomial data.
  63445. */
  63446. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63447. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63448. var totalSolidAngle = 0.0;
  63449. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63450. var du = 2.0 / cubeInfo.size;
  63451. var dv = du;
  63452. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63453. var minUV = du * 0.5 - 1.0;
  63454. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63455. var fileFace = this.FileFaces[faceIndex];
  63456. var dataArray = cubeInfo[fileFace.name];
  63457. var v = minUV;
  63458. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63459. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63460. // Because SP is still linear, so summation is fine in that basis.
  63461. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63462. for (var y = 0; y < cubeInfo.size; y++) {
  63463. var u = minUV;
  63464. for (var x = 0; x < cubeInfo.size; x++) {
  63465. // World direction (not normalised)
  63466. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63467. worldDirection.normalize();
  63468. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63469. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63470. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63471. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63472. // Handle Integer types.
  63473. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63474. r /= 255;
  63475. g /= 255;
  63476. b /= 255;
  63477. }
  63478. // Handle Gamma space textures.
  63479. if (cubeInfo.gammaSpace) {
  63480. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63481. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63482. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63483. }
  63484. var color = new BABYLON.Color3(r, g, b);
  63485. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63486. totalSolidAngle += deltaSolidAngle;
  63487. u += du;
  63488. }
  63489. v += dv;
  63490. }
  63491. }
  63492. // Solid angle for entire sphere is 4*pi
  63493. var sphereSolidAngle = 4.0 * Math.PI;
  63494. // Adjust the solid angle to allow for how many faces we processed.
  63495. var facesProcessed = 6.0;
  63496. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63497. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63498. // This is needed because the numerical integration over the cube uses a
  63499. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63500. // and also to compensate for accumulative error due to float precision in the summation.
  63501. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63502. sphericalHarmonics.scale(correctionFactor);
  63503. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63504. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63505. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63506. };
  63507. CubeMapToSphericalPolynomialTools.FileFaces = [
  63508. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63509. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63510. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63511. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63512. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63513. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63514. ];
  63515. return CubeMapToSphericalPolynomialTools;
  63516. }());
  63517. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63518. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63519. })(BABYLON || (BABYLON = {}));
  63520. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63521. var BABYLON;
  63522. (function (BABYLON) {
  63523. var Internals;
  63524. (function (Internals) {
  63525. /**
  63526. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63527. */
  63528. var PanoramaToCubeMapTools = /** @class */ (function () {
  63529. function PanoramaToCubeMapTools() {
  63530. }
  63531. /**
  63532. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63533. *
  63534. * @param float32Array The source data.
  63535. * @param inputWidth The width of the input panorama.
  63536. * @param inputhHeight The height of the input panorama.
  63537. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63538. * @return The cubemap data
  63539. */
  63540. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63541. if (!float32Array) {
  63542. throw "ConvertPanoramaToCubemap: input cannot be null";
  63543. }
  63544. if (float32Array.length != inputWidth * inputHeight * 3) {
  63545. throw "ConvertPanoramaToCubemap: input size is wrong";
  63546. }
  63547. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63548. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63549. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63550. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63551. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63552. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63553. return {
  63554. front: textureFront,
  63555. back: textureBack,
  63556. left: textureLeft,
  63557. right: textureRight,
  63558. up: textureUp,
  63559. down: textureDown,
  63560. size: size,
  63561. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63562. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63563. gammaSpace: false,
  63564. };
  63565. };
  63566. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63567. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63568. var textureArray = new Float32Array(buffer);
  63569. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63570. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63571. var dy = 1 / texSize;
  63572. var fy = 0;
  63573. for (var y = 0; y < texSize; y++) {
  63574. var xv1 = faceData[0];
  63575. var xv2 = faceData[2];
  63576. for (var x = 0; x < texSize; x++) {
  63577. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63578. v.normalize();
  63579. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63580. // 3 channels per pixels
  63581. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63582. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63583. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63584. xv1 = xv1.add(rotDX1);
  63585. xv2 = xv2.add(rotDX2);
  63586. }
  63587. fy += dy;
  63588. }
  63589. return textureArray;
  63590. };
  63591. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63592. var theta = Math.atan2(vDir.z, vDir.x);
  63593. var phi = Math.acos(vDir.y);
  63594. while (theta < -Math.PI)
  63595. theta += 2 * Math.PI;
  63596. while (theta > Math.PI)
  63597. theta -= 2 * Math.PI;
  63598. var dx = theta / Math.PI;
  63599. var dy = phi / Math.PI;
  63600. // recenter.
  63601. dx = dx * 0.5 + 0.5;
  63602. var px = Math.round(dx * inputWidth);
  63603. if (px < 0)
  63604. px = 0;
  63605. else if (px >= inputWidth)
  63606. px = inputWidth - 1;
  63607. var py = Math.round(dy * inputHeight);
  63608. if (py < 0)
  63609. py = 0;
  63610. else if (py >= inputHeight)
  63611. py = inputHeight - 1;
  63612. var inputY = (inputHeight - py - 1);
  63613. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63614. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63615. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63616. return {
  63617. r: r,
  63618. g: g,
  63619. b: b
  63620. };
  63621. };
  63622. PanoramaToCubeMapTools.FACE_FRONT = [
  63623. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63624. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63625. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63626. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63627. ];
  63628. PanoramaToCubeMapTools.FACE_BACK = [
  63629. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63630. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63631. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63632. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63633. ];
  63634. PanoramaToCubeMapTools.FACE_RIGHT = [
  63635. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63636. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63637. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63638. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63639. ];
  63640. PanoramaToCubeMapTools.FACE_LEFT = [
  63641. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63642. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63643. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63644. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63645. ];
  63646. PanoramaToCubeMapTools.FACE_DOWN = [
  63647. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63648. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63649. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63650. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63651. ];
  63652. PanoramaToCubeMapTools.FACE_UP = [
  63653. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63654. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63655. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63656. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63657. ];
  63658. return PanoramaToCubeMapTools;
  63659. }());
  63660. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63661. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63662. })(BABYLON || (BABYLON = {}));
  63663. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63664. var BABYLON;
  63665. (function (BABYLON) {
  63666. var Internals;
  63667. (function (Internals) {
  63668. ;
  63669. /**
  63670. * This groups tools to convert HDR texture to native colors array.
  63671. */
  63672. var HDRTools = /** @class */ (function () {
  63673. function HDRTools() {
  63674. }
  63675. HDRTools.Ldexp = function (mantissa, exponent) {
  63676. if (exponent > 1023) {
  63677. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63678. }
  63679. if (exponent < -1074) {
  63680. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63681. }
  63682. return mantissa * Math.pow(2, exponent);
  63683. };
  63684. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63685. if (exponent > 0) {
  63686. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63687. float32array[index + 0] = red * exponent;
  63688. float32array[index + 1] = green * exponent;
  63689. float32array[index + 2] = blue * exponent;
  63690. }
  63691. else {
  63692. float32array[index + 0] = 0;
  63693. float32array[index + 1] = 0;
  63694. float32array[index + 2] = 0;
  63695. }
  63696. };
  63697. HDRTools.readStringLine = function (uint8array, startIndex) {
  63698. var line = "";
  63699. var character = "";
  63700. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63701. character = String.fromCharCode(uint8array[i]);
  63702. if (character == "\n") {
  63703. break;
  63704. }
  63705. line += character;
  63706. }
  63707. return line;
  63708. };
  63709. /**
  63710. * Reads header information from an RGBE texture stored in a native array.
  63711. * More information on this format are available here:
  63712. * https://en.wikipedia.org/wiki/RGBE_image_format
  63713. *
  63714. * @param uint8array The binary file stored in native array.
  63715. * @return The header information.
  63716. */
  63717. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63718. var height = 0;
  63719. var width = 0;
  63720. var line = this.readStringLine(uint8array, 0);
  63721. if (line[0] != '#' || line[1] != '?') {
  63722. throw "Bad HDR Format.";
  63723. }
  63724. var endOfHeader = false;
  63725. var findFormat = false;
  63726. var lineIndex = 0;
  63727. do {
  63728. lineIndex += (line.length + 1);
  63729. line = this.readStringLine(uint8array, lineIndex);
  63730. if (line == "FORMAT=32-bit_rle_rgbe") {
  63731. findFormat = true;
  63732. }
  63733. else if (line.length == 0) {
  63734. endOfHeader = true;
  63735. }
  63736. } while (!endOfHeader);
  63737. if (!findFormat) {
  63738. throw "HDR Bad header format, unsupported FORMAT";
  63739. }
  63740. lineIndex += (line.length + 1);
  63741. line = this.readStringLine(uint8array, lineIndex);
  63742. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63743. var match = sizeRegexp.exec(line);
  63744. // TODO. Support +Y and -X if needed.
  63745. if (!match || match.length < 3) {
  63746. throw "HDR Bad header format, no size";
  63747. }
  63748. width = parseInt(match[2]);
  63749. height = parseInt(match[1]);
  63750. if (width < 8 || width > 0x7fff) {
  63751. throw "HDR Bad header format, unsupported size";
  63752. }
  63753. lineIndex += (line.length + 1);
  63754. return {
  63755. height: height,
  63756. width: width,
  63757. dataPosition: lineIndex
  63758. };
  63759. };
  63760. /**
  63761. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63762. * This RGBE texture needs to store the information as a panorama.
  63763. *
  63764. * More information on this format are available here:
  63765. * https://en.wikipedia.org/wiki/RGBE_image_format
  63766. *
  63767. * @param buffer The binary file stored in an array buffer.
  63768. * @param size The expected size of the extracted cubemap.
  63769. * @return The Cube Map information.
  63770. */
  63771. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63772. var uint8array = new Uint8Array(buffer);
  63773. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63774. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63775. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63776. return cubeMapData;
  63777. };
  63778. /**
  63779. * Returns the pixels data extracted from an RGBE texture.
  63780. * This pixels will be stored left to right up to down in the R G B order in one array.
  63781. *
  63782. * More information on this format are available here:
  63783. * https://en.wikipedia.org/wiki/RGBE_image_format
  63784. *
  63785. * @param uint8array The binary file stored in an array buffer.
  63786. * @param hdrInfo The header information of the file.
  63787. * @return The pixels data in RGB right to left up to down order.
  63788. */
  63789. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63790. // Keep for multi format supports.
  63791. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63792. };
  63793. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63794. var num_scanlines = hdrInfo.height;
  63795. var scanline_width = hdrInfo.width;
  63796. var a, b, c, d, count;
  63797. var dataIndex = hdrInfo.dataPosition;
  63798. var index = 0, endIndex = 0, i = 0;
  63799. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63800. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63801. // 3 channels of 4 bytes per pixel in float.
  63802. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63803. var resultArray = new Float32Array(resultBuffer);
  63804. // read in each successive scanline
  63805. while (num_scanlines > 0) {
  63806. a = uint8array[dataIndex++];
  63807. b = uint8array[dataIndex++];
  63808. c = uint8array[dataIndex++];
  63809. d = uint8array[dataIndex++];
  63810. if (a != 2 || b != 2 || (c & 0x80)) {
  63811. // this file is not run length encoded
  63812. throw "HDR Bad header format, not RLE";
  63813. }
  63814. if (((c << 8) | d) != scanline_width) {
  63815. throw "HDR Bad header format, wrong scan line width";
  63816. }
  63817. index = 0;
  63818. // read each of the four channels for the scanline into the buffer
  63819. for (i = 0; i < 4; i++) {
  63820. endIndex = (i + 1) * scanline_width;
  63821. while (index < endIndex) {
  63822. a = uint8array[dataIndex++];
  63823. b = uint8array[dataIndex++];
  63824. if (a > 128) {
  63825. // a run of the same value
  63826. count = a - 128;
  63827. if ((count == 0) || (count > endIndex - index)) {
  63828. throw "HDR Bad Format, bad scanline data (run)";
  63829. }
  63830. while (count-- > 0) {
  63831. scanLineArray[index++] = b;
  63832. }
  63833. }
  63834. else {
  63835. // a non-run
  63836. count = a;
  63837. if ((count == 0) || (count > endIndex - index)) {
  63838. throw "HDR Bad Format, bad scanline data (non-run)";
  63839. }
  63840. scanLineArray[index++] = b;
  63841. if (--count > 0) {
  63842. for (var j = 0; j < count; j++) {
  63843. scanLineArray[index++] = uint8array[dataIndex++];
  63844. }
  63845. }
  63846. }
  63847. }
  63848. }
  63849. // now convert data from buffer into floats
  63850. for (i = 0; i < scanline_width; i++) {
  63851. a = scanLineArray[i];
  63852. b = scanLineArray[i + scanline_width];
  63853. c = scanLineArray[i + 2 * scanline_width];
  63854. d = scanLineArray[i + 3 * scanline_width];
  63855. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63856. }
  63857. num_scanlines--;
  63858. }
  63859. return resultArray;
  63860. };
  63861. return HDRTools;
  63862. }());
  63863. Internals.HDRTools = HDRTools;
  63864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63865. })(BABYLON || (BABYLON = {}));
  63866. //# sourceMappingURL=babylon.hdr.js.map
  63867. var BABYLON;
  63868. (function (BABYLON) {
  63869. /**
  63870. * This represents a texture coming from an HDR input.
  63871. *
  63872. * The only supported format is currently panorama picture stored in RGBE format.
  63873. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63874. */
  63875. var HDRCubeTexture = /** @class */ (function (_super) {
  63876. __extends(HDRCubeTexture, _super);
  63877. /**
  63878. * Instantiates an HDRTexture from the following parameters.
  63879. *
  63880. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63881. * @param scene The scene the texture will be used in
  63882. * @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.
  63883. * @param noMipmap Forces to not generate the mipmap if true
  63884. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63885. * @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)
  63886. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63887. */
  63888. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63889. if (noMipmap === void 0) { noMipmap = false; }
  63890. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63891. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63892. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63893. if (onLoad === void 0) { onLoad = null; }
  63894. if (onError === void 0) { onError = null; }
  63895. var _this = _super.call(this, scene) || this;
  63896. _this._useInGammaSpace = false;
  63897. _this._generateHarmonics = true;
  63898. _this._isBABYLONPreprocessed = false;
  63899. _this._onLoad = null;
  63900. _this._onError = null;
  63901. /**
  63902. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63903. */
  63904. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63905. /**
  63906. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63907. * This is usefull at run time to apply the good shader.
  63908. */
  63909. _this.isPMREM = false;
  63910. _this._isBlocking = true;
  63911. if (!url) {
  63912. return _this;
  63913. }
  63914. _this.name = url;
  63915. _this.url = url;
  63916. _this.hasAlpha = false;
  63917. _this.isCube = true;
  63918. _this._textureMatrix = BABYLON.Matrix.Identity();
  63919. _this._onLoad = onLoad;
  63920. _this._onError = onError;
  63921. _this.gammaSpace = false;
  63922. var caps = scene.getEngine().getCaps();
  63923. if (size) {
  63924. _this._isBABYLONPreprocessed = false;
  63925. _this._noMipmap = noMipmap;
  63926. _this._size = size;
  63927. _this._useInGammaSpace = useInGammaSpace;
  63928. _this._usePMREMGenerator = usePMREMGenerator &&
  63929. caps.textureLOD &&
  63930. caps.textureFloat &&
  63931. !_this._useInGammaSpace;
  63932. }
  63933. else {
  63934. _this._isBABYLONPreprocessed = true;
  63935. _this._noMipmap = false;
  63936. _this._useInGammaSpace = false;
  63937. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63938. !_this._useInGammaSpace;
  63939. }
  63940. _this.isPMREM = _this._usePMREMGenerator;
  63941. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63942. if (!_this._texture) {
  63943. if (!scene.useDelayedTextureLoading) {
  63944. _this.loadTexture();
  63945. }
  63946. else {
  63947. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63948. }
  63949. }
  63950. return _this;
  63951. }
  63952. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63953. /**
  63954. * Gets wether or not the texture is blocking during loading.
  63955. */
  63956. get: function () {
  63957. return this._isBlocking;
  63958. },
  63959. /**
  63960. * Sets wether or not the texture is blocking during loading.
  63961. */
  63962. set: function (value) {
  63963. this._isBlocking = value;
  63964. },
  63965. enumerable: true,
  63966. configurable: true
  63967. });
  63968. /**
  63969. * Occurs when the file is a preprocessed .babylon.hdr file.
  63970. */
  63971. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63972. var _this = this;
  63973. var mipLevels = 0;
  63974. var floatArrayView = null;
  63975. var scene = this.getScene();
  63976. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63977. var mips = new Array();
  63978. if (!floatArrayView) {
  63979. return mips;
  63980. }
  63981. var startIndex = 30;
  63982. for (var level = 0; level < mipLevels; level++) {
  63983. mips.push([]);
  63984. // Fill each pixel of the mip level.
  63985. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63987. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63988. mips[level].push(faceData);
  63989. startIndex += faceSize;
  63990. }
  63991. }
  63992. return mips;
  63993. } : null;
  63994. var callback = function (buffer) {
  63995. var scene = _this.getScene();
  63996. if (!scene) {
  63997. return null;
  63998. }
  63999. // Create Native Array Views
  64000. var intArrayView = new Int32Array(buffer);
  64001. floatArrayView = new Float32Array(buffer);
  64002. // Fill header.
  64003. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64004. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64005. // Update Texture Information.
  64006. if (!_this._texture) {
  64007. return null;
  64008. }
  64009. _this._texture.updateSize(_this._size, _this._size);
  64010. // Fill polynomial information.
  64011. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64012. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64013. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64014. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64015. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64016. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64017. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64018. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64019. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64020. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64021. _this.sphericalPolynomial = sphericalPolynomial;
  64022. // Fill pixel data.
  64023. mipLevels = intArrayView[29]; // Number of mip levels.
  64024. var startIndex = 30;
  64025. var data = [];
  64026. var faceSize = Math.pow(_this._size, 2) * 3;
  64027. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64028. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64029. startIndex += faceSize;
  64030. }
  64031. var results = [];
  64032. var byteArray = null;
  64033. // Push each faces.
  64034. for (var k = 0; k < 6; k++) {
  64035. var dataFace = null;
  64036. // To be deprecated.
  64037. if (version === 1) {
  64038. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64039. dataFace = data[j];
  64040. }
  64041. // If special cases.
  64042. if (!mipmapGenerator && dataFace) {
  64043. if (!scene.getEngine().getCaps().textureFloat) {
  64044. // 3 channels of 1 bytes per pixel in bytes.
  64045. var byteBuffer = new ArrayBuffer(faceSize);
  64046. byteArray = new Uint8Array(byteBuffer);
  64047. }
  64048. for (var i = 0; i < _this._size * _this._size; i++) {
  64049. // Put in gamma space if requested.
  64050. if (_this._useInGammaSpace) {
  64051. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64052. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64053. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64054. }
  64055. // Convert to int texture for fallback.
  64056. if (byteArray) {
  64057. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64058. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64059. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64060. // May use luminance instead if the result is not accurate.
  64061. var max = Math.max(Math.max(r, g), b);
  64062. if (max > 255) {
  64063. var scale = 255 / max;
  64064. r *= scale;
  64065. g *= scale;
  64066. b *= scale;
  64067. }
  64068. byteArray[(i * 3) + 0] = r;
  64069. byteArray[(i * 3) + 1] = g;
  64070. byteArray[(i * 3) + 2] = b;
  64071. }
  64072. }
  64073. }
  64074. // Fill the array accordingly.
  64075. if (byteArray) {
  64076. results.push(byteArray);
  64077. }
  64078. else {
  64079. results.push(dataFace);
  64080. }
  64081. }
  64082. return results;
  64083. };
  64084. if (scene) {
  64085. 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);
  64086. }
  64087. };
  64088. /**
  64089. * Occurs when the file is raw .hdr file.
  64090. */
  64091. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64092. var _this = this;
  64093. var callback = function (buffer) {
  64094. var scene = _this.getScene();
  64095. if (!scene) {
  64096. return null;
  64097. }
  64098. // Extract the raw linear data.
  64099. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64100. // Generate harmonics if needed.
  64101. if (_this._generateHarmonics) {
  64102. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64103. _this.sphericalPolynomial = sphericalPolynomial;
  64104. }
  64105. var results = [];
  64106. var byteArray = null;
  64107. // Push each faces.
  64108. for (var j = 0; j < 6; j++) {
  64109. // Create uintarray fallback.
  64110. if (!scene.getEngine().getCaps().textureFloat) {
  64111. // 3 channels of 1 bytes per pixel in bytes.
  64112. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64113. byteArray = new Uint8Array(byteBuffer);
  64114. }
  64115. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64116. // If special cases.
  64117. if (_this._useInGammaSpace || byteArray) {
  64118. for (var i = 0; i < _this._size * _this._size; i++) {
  64119. // Put in gamma space if requested.
  64120. if (_this._useInGammaSpace) {
  64121. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64122. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64123. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64124. }
  64125. // Convert to int texture for fallback.
  64126. if (byteArray) {
  64127. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64128. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64129. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64130. // May use luminance instead if the result is not accurate.
  64131. var max = Math.max(Math.max(r, g), b);
  64132. if (max > 255) {
  64133. var scale = 255 / max;
  64134. r *= scale;
  64135. g *= scale;
  64136. b *= scale;
  64137. }
  64138. byteArray[(i * 3) + 0] = r;
  64139. byteArray[(i * 3) + 1] = g;
  64140. byteArray[(i * 3) + 2] = b;
  64141. }
  64142. }
  64143. }
  64144. if (byteArray) {
  64145. results.push(byteArray);
  64146. }
  64147. else {
  64148. results.push(dataFace);
  64149. }
  64150. }
  64151. return results;
  64152. };
  64153. var mipmapGenerator = null;
  64154. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64155. // if (!this._noMipmap &&
  64156. // this._usePMREMGenerator) {
  64157. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64158. // // Custom setup of the generator matching with the PBR shader values.
  64159. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64160. // this._size,
  64161. // this._size,
  64162. // 0,
  64163. // 3,
  64164. // this.getScene().getEngine().getCaps().textureFloat,
  64165. // 2048,
  64166. // 0.25,
  64167. // false,
  64168. // true);
  64169. // return generator.filterCubeMap();
  64170. // };
  64171. // }
  64172. var scene = this.getScene();
  64173. if (scene) {
  64174. 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);
  64175. }
  64176. };
  64177. /**
  64178. * Starts the loading process of the texture.
  64179. */
  64180. HDRCubeTexture.prototype.loadTexture = function () {
  64181. if (this._isBABYLONPreprocessed) {
  64182. this.loadBabylonTexture();
  64183. }
  64184. else {
  64185. this.loadHDRTexture();
  64186. }
  64187. };
  64188. HDRCubeTexture.prototype.clone = function () {
  64189. var scene = this.getScene();
  64190. if (!scene) {
  64191. return this;
  64192. }
  64193. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64194. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64195. // Base texture
  64196. newTexture.level = this.level;
  64197. newTexture.wrapU = this.wrapU;
  64198. newTexture.wrapV = this.wrapV;
  64199. newTexture.coordinatesIndex = this.coordinatesIndex;
  64200. newTexture.coordinatesMode = this.coordinatesMode;
  64201. return newTexture;
  64202. };
  64203. // Methods
  64204. HDRCubeTexture.prototype.delayLoad = function () {
  64205. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64206. return;
  64207. }
  64208. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64209. this._texture = this._getFromCache(this.url, this._noMipmap);
  64210. if (!this._texture) {
  64211. this.loadTexture();
  64212. }
  64213. };
  64214. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64215. return this._textureMatrix;
  64216. };
  64217. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64218. this._textureMatrix = value;
  64219. };
  64220. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64221. var texture = null;
  64222. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64223. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64224. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64225. texture.name = parsedTexture.name;
  64226. texture.hasAlpha = parsedTexture.hasAlpha;
  64227. texture.level = parsedTexture.level;
  64228. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64229. texture.isBlocking = parsedTexture.isBlocking;
  64230. }
  64231. return texture;
  64232. };
  64233. HDRCubeTexture.prototype.serialize = function () {
  64234. if (!this.name) {
  64235. return null;
  64236. }
  64237. var serializationObject = {};
  64238. serializationObject.name = this.name;
  64239. serializationObject.hasAlpha = this.hasAlpha;
  64240. serializationObject.isCube = true;
  64241. serializationObject.level = this.level;
  64242. serializationObject.size = this._size;
  64243. serializationObject.coordinatesMode = this.coordinatesMode;
  64244. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64245. serializationObject.generateHarmonics = this._generateHarmonics;
  64246. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64247. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64248. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64249. serializationObject.noMipmap = this._noMipmap;
  64250. serializationObject.isBlocking = this._isBlocking;
  64251. return serializationObject;
  64252. };
  64253. /**
  64254. * Saves as a file the data contained in the texture in a binary format.
  64255. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64256. * as the spherical used in the lighting.
  64257. * @param url The HDR file url.
  64258. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64259. * @param onError Method called if any error happens during download.
  64260. * @return The packed binary data.
  64261. */
  64262. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64263. if (onError === void 0) { onError = null; }
  64264. var callback = function (buffer) {
  64265. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64266. // Returns a URL you can use as a href.
  64267. var objUrl = window.URL.createObjectURL(data);
  64268. // Simulates a link to it and click to dowload.
  64269. var a = document.createElement("a");
  64270. document.body.appendChild(a);
  64271. a.style.display = "none";
  64272. a.href = objUrl;
  64273. a.download = "envmap.babylon.hdr";
  64274. a.click();
  64275. };
  64276. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64277. };
  64278. /**
  64279. * Serializes the data contained in the texture in a binary format.
  64280. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64281. * as the spherical used in the lighting.
  64282. * @param url The HDR file url.
  64283. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64284. * @param onError Method called if any error happens during download.
  64285. * @return The packed binary data.
  64286. */
  64287. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64288. if (onError === void 0) { onError = null; }
  64289. // Needs the url tho create the texture.
  64290. if (!url) {
  64291. return;
  64292. }
  64293. // Check Power of two size.
  64294. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64295. return;
  64296. }
  64297. // Coming Back in 3.x.
  64298. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64299. };
  64300. HDRCubeTexture._facesMapping = [
  64301. "right",
  64302. "left",
  64303. "up",
  64304. "down",
  64305. "front",
  64306. "back"
  64307. ];
  64308. return HDRCubeTexture;
  64309. }(BABYLON.BaseTexture));
  64310. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64311. })(BABYLON || (BABYLON = {}));
  64312. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64313. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64314. // Huge respect for a such great lib.
  64315. // Earcut license:
  64316. // Copyright (c) 2016, Mapbox
  64317. //
  64318. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64319. // with or without fee is hereby granted, provided that the above copyright notice
  64320. // and this permission notice appear in all copies.
  64321. //
  64322. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64323. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64324. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64325. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64326. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64327. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64328. // THIS SOFTWARE.
  64329. var Earcut;
  64330. (function (Earcut) {
  64331. /**
  64332. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64333. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64334. * @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).
  64335. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64336. */
  64337. function earcut(data, holeIndices, dim) {
  64338. dim = dim || 2;
  64339. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64340. if (!outerNode)
  64341. return triangles;
  64342. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64343. if (hasHoles)
  64344. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64345. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64346. if (data.length > 80 * dim) {
  64347. minX = maxX = data[0];
  64348. minY = maxY = data[1];
  64349. for (var i = dim; i < outerLen; i += dim) {
  64350. x = data[i];
  64351. y = data[i + 1];
  64352. if (x < minX)
  64353. minX = x;
  64354. if (y < minY)
  64355. minY = y;
  64356. if (x > maxX)
  64357. maxX = x;
  64358. if (y > maxY)
  64359. maxY = y;
  64360. }
  64361. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64362. size = Math.max(maxX - minX, maxY - minY);
  64363. }
  64364. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64365. return triangles;
  64366. }
  64367. Earcut.earcut = earcut;
  64368. var Node = /** @class */ (function () {
  64369. function Node(i, x, y) {
  64370. this.i = i;
  64371. this.x = x;
  64372. this.y = y;
  64373. this.prev = null;
  64374. this.next = null;
  64375. this.z = null;
  64376. this.prevZ = null;
  64377. this.nextZ = null;
  64378. this.steiner = false;
  64379. }
  64380. return Node;
  64381. }());
  64382. // create a circular doubly linked list from polygon points in the specified winding order
  64383. function linkedList(data, start, end, dim, clockwise) {
  64384. var i, last = null;
  64385. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64386. for (i = start; i < end; i += dim)
  64387. last = insertNode(i, data[i], data[i + 1], last);
  64388. }
  64389. else {
  64390. for (i = end - dim; i >= start; i -= dim)
  64391. last = insertNode(i, data[i], data[i + 1], last);
  64392. }
  64393. if (last && equals(last, last.next)) {
  64394. removeNode(last);
  64395. last = last.next;
  64396. }
  64397. return last;
  64398. }
  64399. // eliminate colinear or duplicate points
  64400. function filterPoints(start, end) {
  64401. if (!start)
  64402. return start;
  64403. if (!end)
  64404. end = start;
  64405. var p = start, again;
  64406. do {
  64407. again = false;
  64408. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64409. removeNode(p);
  64410. p = end = p.prev;
  64411. if (p === p.next)
  64412. return undefined;
  64413. again = true;
  64414. }
  64415. else {
  64416. p = p.next;
  64417. }
  64418. } while (again || p !== end);
  64419. return end;
  64420. }
  64421. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64422. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64423. if (!ear)
  64424. return;
  64425. // interlink polygon nodes in z-order
  64426. if (!pass && size)
  64427. indexCurve(ear, minX, minY, size);
  64428. var stop = ear, prev, next;
  64429. // iterate through ears, slicing them one by one
  64430. while (ear.prev !== ear.next) {
  64431. prev = ear.prev;
  64432. next = ear.next;
  64433. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64434. // cut off the triangle
  64435. triangles.push(prev.i / dim);
  64436. triangles.push(ear.i / dim);
  64437. triangles.push(next.i / dim);
  64438. removeNode(ear);
  64439. // skipping the next vertice leads to less sliver triangles
  64440. ear = next.next;
  64441. stop = next.next;
  64442. continue;
  64443. }
  64444. ear = next;
  64445. // if we looped through the whole remaining polygon and can't find any more ears
  64446. if (ear === stop) {
  64447. // try filtering points and slicing again
  64448. if (!pass) {
  64449. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64450. // if this didn't work, try curing all small self-intersections locally
  64451. }
  64452. else if (pass === 1) {
  64453. ear = cureLocalIntersections(ear, triangles, dim);
  64454. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64455. // as a last resort, try splitting the remaining polygon into two
  64456. }
  64457. else if (pass === 2) {
  64458. splitEarcut(ear, triangles, dim, minX, minY, size);
  64459. }
  64460. break;
  64461. }
  64462. }
  64463. }
  64464. // check whether a polygon node forms a valid ear with adjacent nodes
  64465. function isEar(ear) {
  64466. var a = ear.prev, b = ear, c = ear.next;
  64467. if (area(a, b, c) >= 0)
  64468. return false; // reflex, can't be an ear
  64469. // now make sure we don't have other points inside the potential ear
  64470. var p = ear.next.next;
  64471. while (p !== ear.prev) {
  64472. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64473. area(p.prev, p, p.next) >= 0)
  64474. return false;
  64475. p = p.next;
  64476. }
  64477. return true;
  64478. }
  64479. function isEarHashed(ear, minX, minY, size) {
  64480. var a = ear.prev, b = ear, c = ear.next;
  64481. if (area(a, b, c) >= 0)
  64482. return false; // reflex, can't be an ear
  64483. // triangle bbox; min & max are calculated like this for speed
  64484. 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);
  64485. // z-order range for the current triangle bbox;
  64486. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64487. // first look for points inside the triangle in increasing z-order
  64488. var p = ear.nextZ;
  64489. while (p && p.z <= maxZ) {
  64490. if (p !== ear.prev &&
  64491. p !== ear.next &&
  64492. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64493. area(p.prev, p, p.next) >= 0)
  64494. return false;
  64495. p = p.nextZ;
  64496. }
  64497. // then look for points in decreasing z-order
  64498. p = ear.prevZ;
  64499. while (p && p.z >= minZ) {
  64500. if (p !== ear.prev &&
  64501. p !== ear.next &&
  64502. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64503. area(p.prev, p, p.next) >= 0)
  64504. return false;
  64505. p = p.prevZ;
  64506. }
  64507. return true;
  64508. }
  64509. // go through all polygon nodes and cure small local self-intersections
  64510. function cureLocalIntersections(start, triangles, dim) {
  64511. var p = start;
  64512. do {
  64513. var a = p.prev, b = p.next.next;
  64514. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64515. triangles.push(a.i / dim);
  64516. triangles.push(p.i / dim);
  64517. triangles.push(b.i / dim);
  64518. // remove two nodes involved
  64519. removeNode(p);
  64520. removeNode(p.next);
  64521. p = start = b;
  64522. }
  64523. p = p.next;
  64524. } while (p !== start);
  64525. return p;
  64526. }
  64527. // try splitting polygon into two and triangulate them independently
  64528. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64529. // look for a valid diagonal that divides the polygon into two
  64530. var a = start;
  64531. do {
  64532. var b = a.next.next;
  64533. while (b !== a.prev) {
  64534. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64535. // split the polygon in two by the diagonal
  64536. var c = splitPolygon(a, b);
  64537. // filter colinear points around the cuts
  64538. a = filterPoints(a, a.next);
  64539. c = filterPoints(c, c.next);
  64540. // run earcut on each half
  64541. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64542. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64543. return;
  64544. }
  64545. b = b.next;
  64546. }
  64547. a = a.next;
  64548. } while (a !== start);
  64549. }
  64550. // link every hole into the outer loop, producing a single-ring polygon without holes
  64551. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64552. var queue = [], i, len, start, end, list;
  64553. for (i = 0, len = holeIndices.length; i < len; i++) {
  64554. start = holeIndices[i] * dim;
  64555. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64556. list = linkedList(data, start, end, dim, false);
  64557. if (list === list.next)
  64558. list.steiner = true;
  64559. queue.push(getLeftmost(list));
  64560. }
  64561. queue.sort(compareX);
  64562. // process holes from left to right
  64563. for (i = 0; i < queue.length; i++) {
  64564. eliminateHole(queue[i], outerNode);
  64565. outerNode = filterPoints(outerNode, outerNode.next);
  64566. }
  64567. return outerNode;
  64568. }
  64569. function compareX(a, b) {
  64570. return a.x - b.x;
  64571. }
  64572. // find a bridge between vertices that connects hole with an outer ring and and link it
  64573. function eliminateHole(hole, outerNode) {
  64574. outerNode = findHoleBridge(hole, outerNode);
  64575. if (outerNode) {
  64576. var b = splitPolygon(outerNode, hole);
  64577. filterPoints(b, b.next);
  64578. }
  64579. }
  64580. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64581. function findHoleBridge(hole, outerNode) {
  64582. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64583. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64584. // segment's endpoint with lesser x will be potential connection point
  64585. do {
  64586. if (hy <= p.y && hy >= p.next.y) {
  64587. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64588. if (x <= hx && x > qx) {
  64589. qx = x;
  64590. if (x === hx) {
  64591. if (hy === p.y)
  64592. return p;
  64593. if (hy === p.next.y)
  64594. return p.next;
  64595. }
  64596. m = p.x < p.next.x ? p : p.next;
  64597. }
  64598. }
  64599. p = p.next;
  64600. } while (p !== outerNode);
  64601. if (!m)
  64602. return null;
  64603. if (hx === qx)
  64604. return m.prev; // hole touches outer segment; pick lower endpoint
  64605. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64606. // if there are no points found, we have a valid connection;
  64607. // otherwise choose the point of the minimum angle with the ray as connection point
  64608. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64609. p = m.next;
  64610. while (p !== stop) {
  64611. if (hx >= p.x &&
  64612. p.x >= mx &&
  64613. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64614. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64615. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64616. m = p;
  64617. tanMin = tan;
  64618. }
  64619. }
  64620. p = p.next;
  64621. }
  64622. return m;
  64623. }
  64624. // interlink polygon nodes in z-order
  64625. function indexCurve(start, minX, minY, size) {
  64626. var p = start;
  64627. do {
  64628. if (p.z === null)
  64629. p.z = zOrder(p.x, p.y, minX, minY, size);
  64630. p.prevZ = p.prev;
  64631. p.nextZ = p.next;
  64632. p = p.next;
  64633. } while (p !== start);
  64634. p.prevZ.nextZ = null;
  64635. p.prevZ = null;
  64636. sortLinked(p);
  64637. }
  64638. // Simon Tatham's linked list merge sort algorithm
  64639. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64640. function sortLinked(list) {
  64641. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64642. do {
  64643. p = list;
  64644. list = null;
  64645. tail = null;
  64646. numMerges = 0;
  64647. while (p) {
  64648. numMerges++;
  64649. q = p;
  64650. pSize = 0;
  64651. for (i = 0; i < inSize; i++) {
  64652. pSize++;
  64653. q = q.nextZ;
  64654. if (!q)
  64655. break;
  64656. }
  64657. qSize = inSize;
  64658. while (pSize > 0 || (qSize > 0 && q)) {
  64659. if (pSize === 0) {
  64660. e = q;
  64661. q = q.nextZ;
  64662. qSize--;
  64663. }
  64664. else if (qSize === 0 || !q) {
  64665. e = p;
  64666. p = p.nextZ;
  64667. pSize--;
  64668. }
  64669. else if (p.z <= q.z) {
  64670. e = p;
  64671. p = p.nextZ;
  64672. pSize--;
  64673. }
  64674. else {
  64675. e = q;
  64676. q = q.nextZ;
  64677. qSize--;
  64678. }
  64679. if (tail)
  64680. tail.nextZ = e;
  64681. else
  64682. list = e;
  64683. e.prevZ = tail;
  64684. tail = e;
  64685. }
  64686. p = q;
  64687. }
  64688. tail.nextZ = null;
  64689. inSize *= 2;
  64690. } while (numMerges > 1);
  64691. return list;
  64692. }
  64693. // z-order of a point given coords and size of the data bounding box
  64694. function zOrder(x, y, minX, minY, size) {
  64695. // coords are transformed into non-negative 15-bit integer range
  64696. x = 32767 * (x - minX) / size;
  64697. y = 32767 * (y - minY) / size;
  64698. x = (x | (x << 8)) & 0x00FF00FF;
  64699. x = (x | (x << 4)) & 0x0F0F0F0F;
  64700. x = (x | (x << 2)) & 0x33333333;
  64701. x = (x | (x << 1)) & 0x55555555;
  64702. y = (y | (y << 8)) & 0x00FF00FF;
  64703. y = (y | (y << 4)) & 0x0F0F0F0F;
  64704. y = (y | (y << 2)) & 0x33333333;
  64705. y = (y | (y << 1)) & 0x55555555;
  64706. return x | (y << 1);
  64707. }
  64708. // find the leftmost node of a polygon ring
  64709. function getLeftmost(start) {
  64710. var p = start, leftmost = start;
  64711. do {
  64712. if (p.x < leftmost.x)
  64713. leftmost = p;
  64714. p = p.next;
  64715. } while (p !== start);
  64716. return leftmost;
  64717. }
  64718. // check if a point lies within a convex triangle
  64719. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64720. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64721. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64722. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64723. }
  64724. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64725. function isValidDiagonal(a, b) {
  64726. return a.next.i !== b.i &&
  64727. a.prev.i !== b.i &&
  64728. !intersectsPolygon(a, b) &&
  64729. locallyInside(a, b) &&
  64730. locallyInside(b, a) &&
  64731. middleInside(a, b);
  64732. }
  64733. // signed area of a triangle
  64734. function area(p, q, r) {
  64735. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64736. }
  64737. // check if two points are equal
  64738. function equals(p1, p2) {
  64739. return p1.x === p2.x && p1.y === p2.y;
  64740. }
  64741. // check if two segments intersect
  64742. function intersects(p1, q1, p2, q2) {
  64743. if ((equals(p1, q1) && equals(p2, q2)) ||
  64744. (equals(p1, q2) && equals(p2, q1)))
  64745. return true;
  64746. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64747. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64748. }
  64749. // check if a polygon diagonal intersects any polygon segments
  64750. function intersectsPolygon(a, b) {
  64751. var p = a;
  64752. do {
  64753. if (p.i !== a.i &&
  64754. p.next.i !== a.i &&
  64755. p.i !== b.i &&
  64756. p.next.i !== b.i &&
  64757. intersects(p, p.next, a, b))
  64758. return true;
  64759. p = p.next;
  64760. } while (p !== a);
  64761. return false;
  64762. }
  64763. // check if a polygon diagonal is locally inside the polygon
  64764. function locallyInside(a, b) {
  64765. return area(a.prev, a, a.next) < 0
  64766. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64767. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64768. }
  64769. // check if the middle point of a polygon diagonal is inside the polygon
  64770. function middleInside(a, b) {
  64771. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64772. do {
  64773. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64774. inside = !inside;
  64775. p = p.next;
  64776. } while (p !== a);
  64777. return inside;
  64778. }
  64779. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64780. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64781. function splitPolygon(a, b) {
  64782. 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;
  64783. a.next = b;
  64784. b.prev = a;
  64785. a2.next = an;
  64786. an.prev = a2;
  64787. b2.next = a2;
  64788. a2.prev = b2;
  64789. bp.next = b2;
  64790. b2.prev = bp;
  64791. return b2;
  64792. }
  64793. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64794. function insertNode(i, x, y, last) {
  64795. var p = new Node(i, x, y);
  64796. if (!last) {
  64797. p.prev = p;
  64798. p.next = p;
  64799. }
  64800. else {
  64801. p.next = last.next;
  64802. p.prev = last;
  64803. last.next.prev = p;
  64804. last.next = p;
  64805. }
  64806. return p;
  64807. }
  64808. function removeNode(p) {
  64809. p.next.prev = p.prev;
  64810. p.prev.next = p.next;
  64811. if (p.prevZ)
  64812. p.prevZ.nextZ = p.nextZ;
  64813. if (p.nextZ)
  64814. p.nextZ.prevZ = p.prevZ;
  64815. }
  64816. /**
  64817. * return a percentage difference between the polygon area and its triangulation area;
  64818. * used to verify correctness of triangulation
  64819. */
  64820. function deviation(data, holeIndices, dim, triangles) {
  64821. var hasHoles = holeIndices && holeIndices.length;
  64822. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64823. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64824. if (hasHoles) {
  64825. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64826. var start = holeIndices[i] * dim;
  64827. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64828. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64829. }
  64830. }
  64831. var trianglesArea = 0;
  64832. for (i = 0; i < triangles.length; i += 3) {
  64833. var a = triangles[i] * dim;
  64834. var b = triangles[i + 1] * dim;
  64835. var c = triangles[i + 2] * dim;
  64836. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64837. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64838. }
  64839. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64840. }
  64841. Earcut.deviation = deviation;
  64842. ;
  64843. function signedArea(data, start, end, dim) {
  64844. var sum = 0;
  64845. for (var i = start, j = end - dim; i < end; i += dim) {
  64846. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64847. j = i;
  64848. }
  64849. return sum;
  64850. }
  64851. /**
  64852. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64853. */
  64854. function flatten(data) {
  64855. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64856. for (var i = 0; i < data.length; i++) {
  64857. for (var j = 0; j < data[i].length; j++) {
  64858. for (var d = 0; d < dim; d++)
  64859. result.vertices.push(data[i][j][d]);
  64860. }
  64861. if (i > 0) {
  64862. holeIndex += data[i - 1].length;
  64863. result.holes.push(holeIndex);
  64864. }
  64865. }
  64866. return result;
  64867. }
  64868. Earcut.flatten = flatten;
  64869. ;
  64870. })(Earcut || (Earcut = {}));
  64871. //# sourceMappingURL=babylon.earcut.js.map
  64872. var BABYLON;
  64873. (function (BABYLON) {
  64874. var IndexedVector2 = /** @class */ (function (_super) {
  64875. __extends(IndexedVector2, _super);
  64876. function IndexedVector2(original, index) {
  64877. var _this = _super.call(this, original.x, original.y) || this;
  64878. _this.index = index;
  64879. return _this;
  64880. }
  64881. return IndexedVector2;
  64882. }(BABYLON.Vector2));
  64883. var PolygonPoints = /** @class */ (function () {
  64884. function PolygonPoints() {
  64885. this.elements = new Array();
  64886. }
  64887. PolygonPoints.prototype.add = function (originalPoints) {
  64888. var _this = this;
  64889. var result = new Array();
  64890. originalPoints.forEach(function (point) {
  64891. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64892. var newPoint = new IndexedVector2(point, _this.elements.length);
  64893. result.push(newPoint);
  64894. _this.elements.push(newPoint);
  64895. }
  64896. });
  64897. return result;
  64898. };
  64899. PolygonPoints.prototype.computeBounds = function () {
  64900. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64901. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64902. this.elements.forEach(function (point) {
  64903. // x
  64904. if (point.x < lmin.x) {
  64905. lmin.x = point.x;
  64906. }
  64907. else if (point.x > lmax.x) {
  64908. lmax.x = point.x;
  64909. }
  64910. // y
  64911. if (point.y < lmin.y) {
  64912. lmin.y = point.y;
  64913. }
  64914. else if (point.y > lmax.y) {
  64915. lmax.y = point.y;
  64916. }
  64917. });
  64918. return {
  64919. min: lmin,
  64920. max: lmax,
  64921. width: lmax.x - lmin.x,
  64922. height: lmax.y - lmin.y
  64923. };
  64924. };
  64925. return PolygonPoints;
  64926. }());
  64927. var Polygon = /** @class */ (function () {
  64928. function Polygon() {
  64929. }
  64930. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64931. return [
  64932. new BABYLON.Vector2(xmin, ymin),
  64933. new BABYLON.Vector2(xmax, ymin),
  64934. new BABYLON.Vector2(xmax, ymax),
  64935. new BABYLON.Vector2(xmin, ymax)
  64936. ];
  64937. };
  64938. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64939. if (cx === void 0) { cx = 0; }
  64940. if (cy === void 0) { cy = 0; }
  64941. if (numberOfSides === void 0) { numberOfSides = 32; }
  64942. var result = new Array();
  64943. var angle = 0;
  64944. var increment = (Math.PI * 2) / numberOfSides;
  64945. for (var i = 0; i < numberOfSides; i++) {
  64946. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64947. angle -= increment;
  64948. }
  64949. return result;
  64950. };
  64951. Polygon.Parse = function (input) {
  64952. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64953. var i, result = [];
  64954. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64955. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64956. }
  64957. return result;
  64958. };
  64959. Polygon.StartingAt = function (x, y) {
  64960. return BABYLON.Path2.StartingAt(x, y);
  64961. };
  64962. return Polygon;
  64963. }());
  64964. BABYLON.Polygon = Polygon;
  64965. var PolygonMeshBuilder = /** @class */ (function () {
  64966. function PolygonMeshBuilder(name, contours, scene) {
  64967. this._points = new PolygonPoints();
  64968. this._outlinepoints = new PolygonPoints();
  64969. this._holes = new Array();
  64970. this._epoints = new Array();
  64971. this._eholes = new Array();
  64972. this._name = name;
  64973. this._scene = scene;
  64974. var points;
  64975. if (contours instanceof BABYLON.Path2) {
  64976. points = contours.getPoints();
  64977. }
  64978. else {
  64979. points = contours;
  64980. }
  64981. this._addToepoint(points);
  64982. this._points.add(points);
  64983. this._outlinepoints.add(points);
  64984. }
  64985. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64986. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64987. var p = points_1[_i];
  64988. this._epoints.push(p.x, p.y);
  64989. }
  64990. };
  64991. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64992. this._points.add(hole);
  64993. var holepoints = new PolygonPoints();
  64994. holepoints.add(hole);
  64995. this._holes.push(holepoints);
  64996. this._eholes.push(this._epoints.length / 2);
  64997. this._addToepoint(hole);
  64998. return this;
  64999. };
  65000. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65001. var _this = this;
  65002. if (updatable === void 0) { updatable = false; }
  65003. if (depth === void 0) { depth = 0; }
  65004. var result = new BABYLON.Mesh(this._name, this._scene);
  65005. var normals = new Array();
  65006. var positions = new Array();
  65007. var uvs = new Array();
  65008. var bounds = this._points.computeBounds();
  65009. this._points.elements.forEach(function (p) {
  65010. normals.push(0, 1.0, 0);
  65011. positions.push(p.x, 0, p.y);
  65012. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65013. });
  65014. var indices = new Array();
  65015. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65016. for (var i = 0; i < res.length; i++) {
  65017. indices.push(res[i]);
  65018. }
  65019. if (depth > 0) {
  65020. var positionscount = (positions.length / 3); //get the current pointcount
  65021. this._points.elements.forEach(function (p) {
  65022. normals.push(0, -1.0, 0);
  65023. positions.push(p.x, -depth, p.y);
  65024. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65025. });
  65026. var totalCount = indices.length;
  65027. for (var i = 0; i < totalCount; i += 3) {
  65028. var i0 = indices[i + 0];
  65029. var i1 = indices[i + 1];
  65030. var i2 = indices[i + 2];
  65031. indices.push(i2 + positionscount);
  65032. indices.push(i1 + positionscount);
  65033. indices.push(i0 + positionscount);
  65034. }
  65035. //Add the sides
  65036. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65037. this._holes.forEach(function (hole) {
  65038. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65039. });
  65040. }
  65041. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65042. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65043. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65044. result.setIndices(indices);
  65045. return result;
  65046. };
  65047. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65048. var StartIndex = positions.length / 3;
  65049. var ulength = 0;
  65050. for (var i = 0; i < points.elements.length; i++) {
  65051. var p = points.elements[i];
  65052. var p1;
  65053. if ((i + 1) > points.elements.length - 1) {
  65054. p1 = points.elements[0];
  65055. }
  65056. else {
  65057. p1 = points.elements[i + 1];
  65058. }
  65059. positions.push(p.x, 0, p.y);
  65060. positions.push(p.x, -depth, p.y);
  65061. positions.push(p1.x, 0, p1.y);
  65062. positions.push(p1.x, -depth, p1.y);
  65063. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65064. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65065. var v3 = v2.subtract(v1);
  65066. var v4 = new BABYLON.Vector3(0, 1, 0);
  65067. var vn = BABYLON.Vector3.Cross(v3, v4);
  65068. vn = vn.normalize();
  65069. uvs.push(ulength / bounds.width, 0);
  65070. uvs.push(ulength / bounds.width, 1);
  65071. ulength += v3.length();
  65072. uvs.push((ulength / bounds.width), 0);
  65073. uvs.push((ulength / bounds.width), 1);
  65074. if (!flip) {
  65075. normals.push(-vn.x, -vn.y, -vn.z);
  65076. normals.push(-vn.x, -vn.y, -vn.z);
  65077. normals.push(-vn.x, -vn.y, -vn.z);
  65078. normals.push(-vn.x, -vn.y, -vn.z);
  65079. indices.push(StartIndex);
  65080. indices.push(StartIndex + 1);
  65081. indices.push(StartIndex + 2);
  65082. indices.push(StartIndex + 1);
  65083. indices.push(StartIndex + 3);
  65084. indices.push(StartIndex + 2);
  65085. }
  65086. else {
  65087. normals.push(vn.x, vn.y, vn.z);
  65088. normals.push(vn.x, vn.y, vn.z);
  65089. normals.push(vn.x, vn.y, vn.z);
  65090. normals.push(vn.x, vn.y, vn.z);
  65091. indices.push(StartIndex);
  65092. indices.push(StartIndex + 2);
  65093. indices.push(StartIndex + 1);
  65094. indices.push(StartIndex + 1);
  65095. indices.push(StartIndex + 2);
  65096. indices.push(StartIndex + 3);
  65097. }
  65098. StartIndex += 4;
  65099. }
  65100. ;
  65101. };
  65102. return PolygonMeshBuilder;
  65103. }());
  65104. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65105. })(BABYLON || (BABYLON = {}));
  65106. //# sourceMappingURL=babylon.polygonMesh.js.map
  65107. var BABYLON;
  65108. (function (BABYLON) {
  65109. // Unique ID when we import meshes from Babylon to CSG
  65110. var currentCSGMeshId = 0;
  65111. // # class Vertex
  65112. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65113. // one to provide additional features like texture coordinates and vertex
  65114. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65115. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65116. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65117. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65118. // is not used anywhere else.
  65119. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65120. var Vertex = /** @class */ (function () {
  65121. function Vertex(pos, normal, uv) {
  65122. this.pos = pos;
  65123. this.normal = normal;
  65124. this.uv = uv;
  65125. }
  65126. Vertex.prototype.clone = function () {
  65127. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65128. };
  65129. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65130. // orientation of a polygon is flipped.
  65131. Vertex.prototype.flip = function () {
  65132. this.normal = this.normal.scale(-1);
  65133. };
  65134. // Create a new vertex between this vertex and `other` by linearly
  65135. // interpolating all properties using a parameter of `t`. Subclasses should
  65136. // override this to interpolate additional properties.
  65137. Vertex.prototype.interpolate = function (other, t) {
  65138. 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));
  65139. };
  65140. return Vertex;
  65141. }());
  65142. // # class Plane
  65143. // Represents a plane in 3D space.
  65144. var Plane = /** @class */ (function () {
  65145. function Plane(normal, w) {
  65146. this.normal = normal;
  65147. this.w = w;
  65148. }
  65149. Plane.FromPoints = function (a, b, c) {
  65150. var v0 = c.subtract(a);
  65151. var v1 = b.subtract(a);
  65152. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65153. return null;
  65154. }
  65155. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65156. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65157. };
  65158. Plane.prototype.clone = function () {
  65159. return new Plane(this.normal.clone(), this.w);
  65160. };
  65161. Plane.prototype.flip = function () {
  65162. this.normal.scaleInPlace(-1);
  65163. this.w = -this.w;
  65164. };
  65165. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65166. // fragments in the appropriate lists. Coplanar polygons go into either
  65167. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65168. // respect to this plane. Polygons in front or in back of this plane go into
  65169. // either `front` or `back`.
  65170. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65171. var COPLANAR = 0;
  65172. var FRONT = 1;
  65173. var BACK = 2;
  65174. var SPANNING = 3;
  65175. // Classify each point as well as the entire polygon into one of the above
  65176. // four classes.
  65177. var polygonType = 0;
  65178. var types = [];
  65179. var i;
  65180. var t;
  65181. for (i = 0; i < polygon.vertices.length; i++) {
  65182. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65183. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65184. polygonType |= type;
  65185. types.push(type);
  65186. }
  65187. // Put the polygon in the correct list, splitting it when necessary.
  65188. switch (polygonType) {
  65189. case COPLANAR:
  65190. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65191. break;
  65192. case FRONT:
  65193. front.push(polygon);
  65194. break;
  65195. case BACK:
  65196. back.push(polygon);
  65197. break;
  65198. case SPANNING:
  65199. var f = [], b = [];
  65200. for (i = 0; i < polygon.vertices.length; i++) {
  65201. var j = (i + 1) % polygon.vertices.length;
  65202. var ti = types[i], tj = types[j];
  65203. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65204. if (ti !== BACK)
  65205. f.push(vi);
  65206. if (ti !== FRONT)
  65207. b.push(ti !== BACK ? vi.clone() : vi);
  65208. if ((ti | tj) === SPANNING) {
  65209. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65210. var v = vi.interpolate(vj, t);
  65211. f.push(v);
  65212. b.push(v.clone());
  65213. }
  65214. }
  65215. var poly;
  65216. if (f.length >= 3) {
  65217. poly = new Polygon(f, polygon.shared);
  65218. if (poly.plane)
  65219. front.push(poly);
  65220. }
  65221. if (b.length >= 3) {
  65222. poly = new Polygon(b, polygon.shared);
  65223. if (poly.plane)
  65224. back.push(poly);
  65225. }
  65226. break;
  65227. }
  65228. };
  65229. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65230. // point is on the plane.
  65231. Plane.EPSILON = 1e-5;
  65232. return Plane;
  65233. }());
  65234. // # class Polygon
  65235. // Represents a convex polygon. The vertices used to initialize a polygon must
  65236. // be coplanar and form a convex loop.
  65237. //
  65238. // Each convex polygon has a `shared` property, which is shared between all
  65239. // polygons that are clones of each other or were split from the same polygon.
  65240. // This can be used to define per-polygon properties (such as surface color).
  65241. var Polygon = /** @class */ (function () {
  65242. function Polygon(vertices, shared) {
  65243. this.vertices = vertices;
  65244. this.shared = shared;
  65245. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65246. }
  65247. Polygon.prototype.clone = function () {
  65248. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65249. return new Polygon(vertices, this.shared);
  65250. };
  65251. Polygon.prototype.flip = function () {
  65252. this.vertices.reverse().map(function (v) { v.flip(); });
  65253. this.plane.flip();
  65254. };
  65255. return Polygon;
  65256. }());
  65257. // # class Node
  65258. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65259. // by picking a polygon to split along. That polygon (and all other coplanar
  65260. // polygons) are added directly to that node and the other polygons are added to
  65261. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65262. // no distinction between internal and leaf nodes.
  65263. var Node = /** @class */ (function () {
  65264. function Node(polygons) {
  65265. this.plane = null;
  65266. this.front = null;
  65267. this.back = null;
  65268. this.polygons = new Array();
  65269. if (polygons) {
  65270. this.build(polygons);
  65271. }
  65272. }
  65273. Node.prototype.clone = function () {
  65274. var node = new Node();
  65275. node.plane = this.plane && this.plane.clone();
  65276. node.front = this.front && this.front.clone();
  65277. node.back = this.back && this.back.clone();
  65278. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65279. return node;
  65280. };
  65281. // Convert solid space to empty space and empty space to solid space.
  65282. Node.prototype.invert = function () {
  65283. for (var i = 0; i < this.polygons.length; i++) {
  65284. this.polygons[i].flip();
  65285. }
  65286. if (this.plane) {
  65287. this.plane.flip();
  65288. }
  65289. if (this.front) {
  65290. this.front.invert();
  65291. }
  65292. if (this.back) {
  65293. this.back.invert();
  65294. }
  65295. var temp = this.front;
  65296. this.front = this.back;
  65297. this.back = temp;
  65298. };
  65299. // Recursively remove all polygons in `polygons` that are inside this BSP
  65300. // tree.
  65301. Node.prototype.clipPolygons = function (polygons) {
  65302. if (!this.plane)
  65303. return polygons.slice();
  65304. var front = new Array(), back = new Array();
  65305. for (var i = 0; i < polygons.length; i++) {
  65306. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65307. }
  65308. if (this.front) {
  65309. front = this.front.clipPolygons(front);
  65310. }
  65311. if (this.back) {
  65312. back = this.back.clipPolygons(back);
  65313. }
  65314. else {
  65315. back = [];
  65316. }
  65317. return front.concat(back);
  65318. };
  65319. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65320. // `bsp`.
  65321. Node.prototype.clipTo = function (bsp) {
  65322. this.polygons = bsp.clipPolygons(this.polygons);
  65323. if (this.front)
  65324. this.front.clipTo(bsp);
  65325. if (this.back)
  65326. this.back.clipTo(bsp);
  65327. };
  65328. // Return a list of all polygons in this BSP tree.
  65329. Node.prototype.allPolygons = function () {
  65330. var polygons = this.polygons.slice();
  65331. if (this.front)
  65332. polygons = polygons.concat(this.front.allPolygons());
  65333. if (this.back)
  65334. polygons = polygons.concat(this.back.allPolygons());
  65335. return polygons;
  65336. };
  65337. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65338. // new polygons are filtered down to the bottom of the tree and become new
  65339. // nodes there. Each set of polygons is partitioned using the first polygon
  65340. // (no heuristic is used to pick a good split).
  65341. Node.prototype.build = function (polygons) {
  65342. if (!polygons.length)
  65343. return;
  65344. if (!this.plane)
  65345. this.plane = polygons[0].plane.clone();
  65346. var front = new Array(), back = new Array();
  65347. for (var i = 0; i < polygons.length; i++) {
  65348. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65349. }
  65350. if (front.length) {
  65351. if (!this.front)
  65352. this.front = new Node();
  65353. this.front.build(front);
  65354. }
  65355. if (back.length) {
  65356. if (!this.back)
  65357. this.back = new Node();
  65358. this.back.build(back);
  65359. }
  65360. };
  65361. return Node;
  65362. }());
  65363. var CSG = /** @class */ (function () {
  65364. function CSG() {
  65365. this.polygons = new Array();
  65366. }
  65367. // Convert BABYLON.Mesh to BABYLON.CSG
  65368. CSG.FromMesh = function (mesh) {
  65369. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65370. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65371. if (mesh instanceof BABYLON.Mesh) {
  65372. mesh.computeWorldMatrix(true);
  65373. matrix = mesh.getWorldMatrix();
  65374. meshPosition = mesh.position.clone();
  65375. meshRotation = mesh.rotation.clone();
  65376. if (mesh.rotationQuaternion) {
  65377. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65378. }
  65379. meshScaling = mesh.scaling.clone();
  65380. }
  65381. else {
  65382. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65383. }
  65384. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65385. var subMeshes = mesh.subMeshes;
  65386. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65387. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65388. vertices = [];
  65389. for (var j = 0; j < 3; j++) {
  65390. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65391. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65392. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65393. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65394. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65395. vertex = new Vertex(position, normal, uv);
  65396. vertices.push(vertex);
  65397. }
  65398. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65399. // To handle the case of degenerated triangle
  65400. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65401. if (polygon.plane)
  65402. polygons.push(polygon);
  65403. }
  65404. }
  65405. var csg = CSG.FromPolygons(polygons);
  65406. csg.matrix = matrix;
  65407. csg.position = meshPosition;
  65408. csg.rotation = meshRotation;
  65409. csg.scaling = meshScaling;
  65410. csg.rotationQuaternion = meshRotationQuaternion;
  65411. currentCSGMeshId++;
  65412. return csg;
  65413. };
  65414. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65415. CSG.FromPolygons = function (polygons) {
  65416. var csg = new CSG();
  65417. csg.polygons = polygons;
  65418. return csg;
  65419. };
  65420. CSG.prototype.clone = function () {
  65421. var csg = new CSG();
  65422. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65423. csg.copyTransformAttributes(this);
  65424. return csg;
  65425. };
  65426. CSG.prototype.union = function (csg) {
  65427. var a = new Node(this.clone().polygons);
  65428. var b = new Node(csg.clone().polygons);
  65429. a.clipTo(b);
  65430. b.clipTo(a);
  65431. b.invert();
  65432. b.clipTo(a);
  65433. b.invert();
  65434. a.build(b.allPolygons());
  65435. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65436. };
  65437. CSG.prototype.unionInPlace = function (csg) {
  65438. var a = new Node(this.polygons);
  65439. var b = new Node(csg.polygons);
  65440. a.clipTo(b);
  65441. b.clipTo(a);
  65442. b.invert();
  65443. b.clipTo(a);
  65444. b.invert();
  65445. a.build(b.allPolygons());
  65446. this.polygons = a.allPolygons();
  65447. };
  65448. CSG.prototype.subtract = function (csg) {
  65449. var a = new Node(this.clone().polygons);
  65450. var b = new Node(csg.clone().polygons);
  65451. a.invert();
  65452. a.clipTo(b);
  65453. b.clipTo(a);
  65454. b.invert();
  65455. b.clipTo(a);
  65456. b.invert();
  65457. a.build(b.allPolygons());
  65458. a.invert();
  65459. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65460. };
  65461. CSG.prototype.subtractInPlace = function (csg) {
  65462. var a = new Node(this.polygons);
  65463. var b = new Node(csg.polygons);
  65464. a.invert();
  65465. a.clipTo(b);
  65466. b.clipTo(a);
  65467. b.invert();
  65468. b.clipTo(a);
  65469. b.invert();
  65470. a.build(b.allPolygons());
  65471. a.invert();
  65472. this.polygons = a.allPolygons();
  65473. };
  65474. CSG.prototype.intersect = function (csg) {
  65475. var a = new Node(this.clone().polygons);
  65476. var b = new Node(csg.clone().polygons);
  65477. a.invert();
  65478. b.clipTo(a);
  65479. b.invert();
  65480. a.clipTo(b);
  65481. b.clipTo(a);
  65482. a.build(b.allPolygons());
  65483. a.invert();
  65484. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65485. };
  65486. CSG.prototype.intersectInPlace = function (csg) {
  65487. var a = new Node(this.polygons);
  65488. var b = new Node(csg.polygons);
  65489. a.invert();
  65490. b.clipTo(a);
  65491. b.invert();
  65492. a.clipTo(b);
  65493. b.clipTo(a);
  65494. a.build(b.allPolygons());
  65495. a.invert();
  65496. this.polygons = a.allPolygons();
  65497. };
  65498. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65499. // not modified.
  65500. CSG.prototype.inverse = function () {
  65501. var csg = this.clone();
  65502. csg.inverseInPlace();
  65503. return csg;
  65504. };
  65505. CSG.prototype.inverseInPlace = function () {
  65506. this.polygons.map(function (p) { p.flip(); });
  65507. };
  65508. // This is used to keep meshes transformations so they can be restored
  65509. // when we build back a Babylon Mesh
  65510. // NB : All CSG operations are performed in world coordinates
  65511. CSG.prototype.copyTransformAttributes = function (csg) {
  65512. this.matrix = csg.matrix;
  65513. this.position = csg.position;
  65514. this.rotation = csg.rotation;
  65515. this.scaling = csg.scaling;
  65516. this.rotationQuaternion = csg.rotationQuaternion;
  65517. return this;
  65518. };
  65519. // Build Raw mesh from CSG
  65520. // Coordinates here are in world space
  65521. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65522. var matrix = this.matrix.clone();
  65523. matrix.invert();
  65524. 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;
  65525. if (keepSubMeshes) {
  65526. // Sort Polygons, since subMeshes are indices range
  65527. polygons.sort(function (a, b) {
  65528. if (a.shared.meshId === b.shared.meshId) {
  65529. return a.shared.subMeshId - b.shared.subMeshId;
  65530. }
  65531. else {
  65532. return a.shared.meshId - b.shared.meshId;
  65533. }
  65534. });
  65535. }
  65536. for (var i = 0, il = polygons.length; i < il; i++) {
  65537. polygon = polygons[i];
  65538. // Building SubMeshes
  65539. if (!subMesh_dict[polygon.shared.meshId]) {
  65540. subMesh_dict[polygon.shared.meshId] = {};
  65541. }
  65542. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65543. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65544. indexStart: +Infinity,
  65545. indexEnd: -Infinity,
  65546. materialIndex: polygon.shared.materialIndex
  65547. };
  65548. }
  65549. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65550. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65551. polygonIndices[0] = 0;
  65552. polygonIndices[1] = j - 1;
  65553. polygonIndices[2] = j;
  65554. for (var k = 0; k < 3; k++) {
  65555. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65556. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65557. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65558. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65559. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65560. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65561. // Check if 2 points can be merged
  65562. if (!(typeof vertex_idx !== 'undefined' &&
  65563. normals[vertex_idx * 3] === localNormal.x &&
  65564. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65565. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65566. uvs[vertex_idx * 2] === uv.x &&
  65567. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65568. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65569. uvs.push(uv.x, uv.y);
  65570. normals.push(normal.x, normal.y, normal.z);
  65571. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65572. }
  65573. indices.push(vertex_idx);
  65574. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65575. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65576. currentIndex++;
  65577. }
  65578. }
  65579. }
  65580. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65581. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65582. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65583. mesh.setIndices(indices, null);
  65584. if (keepSubMeshes) {
  65585. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65586. var materialIndexOffset = 0, materialMaxIndex;
  65587. mesh.subMeshes = new Array();
  65588. for (var m in subMesh_dict) {
  65589. materialMaxIndex = -1;
  65590. for (var sm in subMesh_dict[m]) {
  65591. subMesh_obj = subMesh_dict[m][sm];
  65592. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65593. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65594. }
  65595. materialIndexOffset += ++materialMaxIndex;
  65596. }
  65597. }
  65598. return mesh;
  65599. };
  65600. // Build Mesh from CSG taking material and transforms into account
  65601. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65602. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65603. mesh.material = material;
  65604. mesh.position.copyFrom(this.position);
  65605. mesh.rotation.copyFrom(this.rotation);
  65606. if (this.rotationQuaternion) {
  65607. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65608. }
  65609. mesh.scaling.copyFrom(this.scaling);
  65610. mesh.computeWorldMatrix(true);
  65611. return mesh;
  65612. };
  65613. return CSG;
  65614. }());
  65615. BABYLON.CSG = CSG;
  65616. })(BABYLON || (BABYLON = {}));
  65617. //# sourceMappingURL=babylon.csg.js.map
  65618. var BABYLON;
  65619. (function (BABYLON) {
  65620. var LensFlare = /** @class */ (function () {
  65621. function LensFlare(size, position, color, imgUrl, system) {
  65622. this.size = size;
  65623. this.position = position;
  65624. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65625. this.color = color || new BABYLON.Color3(1, 1, 1);
  65626. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65627. this._system = system;
  65628. system.lensFlares.push(this);
  65629. }
  65630. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65631. return new LensFlare(size, position, color, imgUrl, system);
  65632. };
  65633. LensFlare.prototype.dispose = function () {
  65634. if (this.texture) {
  65635. this.texture.dispose();
  65636. }
  65637. // Remove from scene
  65638. var index = this._system.lensFlares.indexOf(this);
  65639. this._system.lensFlares.splice(index, 1);
  65640. };
  65641. ;
  65642. return LensFlare;
  65643. }());
  65644. BABYLON.LensFlare = LensFlare;
  65645. })(BABYLON || (BABYLON = {}));
  65646. //# sourceMappingURL=babylon.lensFlare.js.map
  65647. var BABYLON;
  65648. (function (BABYLON) {
  65649. var LensFlareSystem = /** @class */ (function () {
  65650. function LensFlareSystem(name, emitter, scene) {
  65651. this.name = name;
  65652. this.lensFlares = new Array();
  65653. this.borderLimit = 300;
  65654. this.viewportBorder = 0;
  65655. this.layerMask = 0x0FFFFFFF;
  65656. this._vertexBuffers = {};
  65657. this._isEnabled = true;
  65658. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65659. this._emitter = emitter;
  65660. this.id = name;
  65661. scene.lensFlareSystems.push(this);
  65662. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65663. var engine = scene.getEngine();
  65664. // VBO
  65665. var vertices = [];
  65666. vertices.push(1, 1);
  65667. vertices.push(-1, 1);
  65668. vertices.push(-1, -1);
  65669. vertices.push(1, -1);
  65670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65671. // Indices
  65672. var indices = [];
  65673. indices.push(0);
  65674. indices.push(1);
  65675. indices.push(2);
  65676. indices.push(0);
  65677. indices.push(2);
  65678. indices.push(3);
  65679. this._indexBuffer = engine.createIndexBuffer(indices);
  65680. // Effects
  65681. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65682. }
  65683. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65684. get: function () {
  65685. return this._isEnabled;
  65686. },
  65687. set: function (value) {
  65688. this._isEnabled = value;
  65689. },
  65690. enumerable: true,
  65691. configurable: true
  65692. });
  65693. LensFlareSystem.prototype.getScene = function () {
  65694. return this._scene;
  65695. };
  65696. LensFlareSystem.prototype.getEmitter = function () {
  65697. return this._emitter;
  65698. };
  65699. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65700. this._emitter = newEmitter;
  65701. };
  65702. LensFlareSystem.prototype.getEmitterPosition = function () {
  65703. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65704. };
  65705. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65706. var position = this.getEmitterPosition();
  65707. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65708. this._positionX = position.x;
  65709. this._positionY = position.y;
  65710. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65711. if (this.viewportBorder > 0) {
  65712. globalViewport.x -= this.viewportBorder;
  65713. globalViewport.y -= this.viewportBorder;
  65714. globalViewport.width += this.viewportBorder * 2;
  65715. globalViewport.height += this.viewportBorder * 2;
  65716. position.x += this.viewportBorder;
  65717. position.y += this.viewportBorder;
  65718. this._positionX += this.viewportBorder;
  65719. this._positionY += this.viewportBorder;
  65720. }
  65721. if (position.z > 0) {
  65722. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65723. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65724. return true;
  65725. }
  65726. return true;
  65727. }
  65728. return false;
  65729. };
  65730. LensFlareSystem.prototype._isVisible = function () {
  65731. if (!this._isEnabled || !this._scene.activeCamera) {
  65732. return false;
  65733. }
  65734. var emitterPosition = this.getEmitterPosition();
  65735. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65736. var distance = direction.length();
  65737. direction.normalize();
  65738. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65739. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65740. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65741. };
  65742. LensFlareSystem.prototype.render = function () {
  65743. if (!this._effect.isReady() || !this._scene.activeCamera)
  65744. return false;
  65745. var engine = this._scene.getEngine();
  65746. var viewport = this._scene.activeCamera.viewport;
  65747. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65748. // Position
  65749. if (!this.computeEffectivePosition(globalViewport)) {
  65750. return false;
  65751. }
  65752. // Visibility
  65753. if (!this._isVisible()) {
  65754. return false;
  65755. }
  65756. // Intensity
  65757. var awayX;
  65758. var awayY;
  65759. if (this._positionX < this.borderLimit + globalViewport.x) {
  65760. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65761. }
  65762. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65763. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65764. }
  65765. else {
  65766. awayX = 0;
  65767. }
  65768. if (this._positionY < this.borderLimit + globalViewport.y) {
  65769. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65770. }
  65771. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65772. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65773. }
  65774. else {
  65775. awayY = 0;
  65776. }
  65777. var away = (awayX > awayY) ? awayX : awayY;
  65778. away -= this.viewportBorder;
  65779. if (away > this.borderLimit) {
  65780. away = this.borderLimit;
  65781. }
  65782. var intensity = 1.0 - (away / this.borderLimit);
  65783. if (intensity < 0) {
  65784. return false;
  65785. }
  65786. if (intensity > 1.0) {
  65787. intensity = 1.0;
  65788. }
  65789. if (this.viewportBorder > 0) {
  65790. globalViewport.x += this.viewportBorder;
  65791. globalViewport.y += this.viewportBorder;
  65792. globalViewport.width -= this.viewportBorder * 2;
  65793. globalViewport.height -= this.viewportBorder * 2;
  65794. this._positionX -= this.viewportBorder;
  65795. this._positionY -= this.viewportBorder;
  65796. }
  65797. // Position
  65798. var centerX = globalViewport.x + globalViewport.width / 2;
  65799. var centerY = globalViewport.y + globalViewport.height / 2;
  65800. var distX = centerX - this._positionX;
  65801. var distY = centerY - this._positionY;
  65802. // Effects
  65803. engine.enableEffect(this._effect);
  65804. engine.setState(false);
  65805. engine.setDepthBuffer(false);
  65806. // VBOs
  65807. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65808. // Flares
  65809. for (var index = 0; index < this.lensFlares.length; index++) {
  65810. var flare = this.lensFlares[index];
  65811. engine.setAlphaMode(flare.alphaMode);
  65812. var x = centerX - (distX * flare.position);
  65813. var y = centerY - (distY * flare.position);
  65814. var cw = flare.size;
  65815. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65816. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65817. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65818. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65819. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65820. // Texture
  65821. this._effect.setTexture("textureSampler", flare.texture);
  65822. // Color
  65823. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65824. // Draw order
  65825. engine.draw(true, 0, 6);
  65826. }
  65827. engine.setDepthBuffer(true);
  65828. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65829. return true;
  65830. };
  65831. LensFlareSystem.prototype.dispose = function () {
  65832. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65833. if (vertexBuffer) {
  65834. vertexBuffer.dispose();
  65835. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65836. }
  65837. if (this._indexBuffer) {
  65838. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65839. this._indexBuffer = null;
  65840. }
  65841. while (this.lensFlares.length) {
  65842. this.lensFlares[0].dispose();
  65843. }
  65844. // Remove from scene
  65845. var index = this._scene.lensFlareSystems.indexOf(this);
  65846. this._scene.lensFlareSystems.splice(index, 1);
  65847. };
  65848. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65849. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65850. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65851. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65852. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65853. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65854. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65855. var parsedFlare = parsedLensFlareSystem.flares[index];
  65856. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65857. }
  65858. return lensFlareSystem;
  65859. };
  65860. LensFlareSystem.prototype.serialize = function () {
  65861. var serializationObject = {};
  65862. serializationObject.id = this.id;
  65863. serializationObject.name = this.name;
  65864. serializationObject.emitterId = this.getEmitter().id;
  65865. serializationObject.borderLimit = this.borderLimit;
  65866. serializationObject.flares = [];
  65867. for (var index = 0; index < this.lensFlares.length; index++) {
  65868. var flare = this.lensFlares[index];
  65869. serializationObject.flares.push({
  65870. size: flare.size,
  65871. position: flare.position,
  65872. color: flare.color.asArray(),
  65873. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65874. });
  65875. }
  65876. return serializationObject;
  65877. };
  65878. return LensFlareSystem;
  65879. }());
  65880. BABYLON.LensFlareSystem = LensFlareSystem;
  65881. })(BABYLON || (BABYLON = {}));
  65882. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65883. var BABYLON;
  65884. (function (BABYLON) {
  65885. /**
  65886. * This is a holder class for the physics joint created by the physics plugin.
  65887. * It holds a set of functions to control the underlying joint.
  65888. */
  65889. var PhysicsJoint = /** @class */ (function () {
  65890. function PhysicsJoint(type, jointData) {
  65891. this.type = type;
  65892. this.jointData = jointData;
  65893. jointData.nativeParams = jointData.nativeParams || {};
  65894. }
  65895. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65896. get: function () {
  65897. return this._physicsJoint;
  65898. },
  65899. set: function (newJoint) {
  65900. if (this._physicsJoint) {
  65901. //remove from the wolrd
  65902. }
  65903. this._physicsJoint = newJoint;
  65904. },
  65905. enumerable: true,
  65906. configurable: true
  65907. });
  65908. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65909. set: function (physicsPlugin) {
  65910. this._physicsPlugin = physicsPlugin;
  65911. },
  65912. enumerable: true,
  65913. configurable: true
  65914. });
  65915. /**
  65916. * Execute a function that is physics-plugin specific.
  65917. * @param {Function} func the function that will be executed.
  65918. * It accepts two parameters: the physics world and the physics joint.
  65919. */
  65920. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65921. func(this._physicsPlugin.world, this._physicsJoint);
  65922. };
  65923. //TODO check if the native joints are the same
  65924. //Joint Types
  65925. PhysicsJoint.DistanceJoint = 0;
  65926. PhysicsJoint.HingeJoint = 1;
  65927. PhysicsJoint.BallAndSocketJoint = 2;
  65928. PhysicsJoint.WheelJoint = 3;
  65929. PhysicsJoint.SliderJoint = 4;
  65930. //OIMO
  65931. PhysicsJoint.PrismaticJoint = 5;
  65932. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65933. PhysicsJoint.UniversalJoint = 6;
  65934. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65935. //Cannon
  65936. //Similar to a Ball-Joint. Different in params
  65937. PhysicsJoint.PointToPointJoint = 8;
  65938. //Cannon only at the moment
  65939. PhysicsJoint.SpringJoint = 9;
  65940. PhysicsJoint.LockJoint = 10;
  65941. return PhysicsJoint;
  65942. }());
  65943. BABYLON.PhysicsJoint = PhysicsJoint;
  65944. /**
  65945. * A class representing a physics distance joint.
  65946. */
  65947. var DistanceJoint = /** @class */ (function (_super) {
  65948. __extends(DistanceJoint, _super);
  65949. function DistanceJoint(jointData) {
  65950. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65951. }
  65952. /**
  65953. * Update the predefined distance.
  65954. */
  65955. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65956. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65957. };
  65958. return DistanceJoint;
  65959. }(PhysicsJoint));
  65960. BABYLON.DistanceJoint = DistanceJoint;
  65961. var MotorEnabledJoint = /** @class */ (function (_super) {
  65962. __extends(MotorEnabledJoint, _super);
  65963. function MotorEnabledJoint(type, jointData) {
  65964. return _super.call(this, type, jointData) || this;
  65965. }
  65966. /**
  65967. * Set the motor values.
  65968. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65969. * @param {number} force the force to apply
  65970. * @param {number} maxForce max force for this motor.
  65971. */
  65972. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65973. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65974. };
  65975. /**
  65976. * Set the motor's limits.
  65977. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65978. */
  65979. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65980. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65981. };
  65982. return MotorEnabledJoint;
  65983. }(PhysicsJoint));
  65984. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65985. /**
  65986. * This class represents a single hinge physics joint
  65987. */
  65988. var HingeJoint = /** @class */ (function (_super) {
  65989. __extends(HingeJoint, _super);
  65990. function HingeJoint(jointData) {
  65991. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65992. }
  65993. /**
  65994. * Set the motor values.
  65995. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65996. * @param {number} force the force to apply
  65997. * @param {number} maxForce max force for this motor.
  65998. */
  65999. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66000. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66001. };
  66002. /**
  66003. * Set the motor's limits.
  66004. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66005. */
  66006. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66007. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66008. };
  66009. return HingeJoint;
  66010. }(MotorEnabledJoint));
  66011. BABYLON.HingeJoint = HingeJoint;
  66012. /**
  66013. * This class represents a dual hinge physics joint (same as wheel joint)
  66014. */
  66015. var Hinge2Joint = /** @class */ (function (_super) {
  66016. __extends(Hinge2Joint, _super);
  66017. function Hinge2Joint(jointData) {
  66018. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66019. }
  66020. /**
  66021. * Set the motor values.
  66022. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66023. * @param {number} force the force to apply
  66024. * @param {number} maxForce max force for this motor.
  66025. * @param {motorIndex} the motor's index, 0 or 1.
  66026. */
  66027. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66028. if (motorIndex === void 0) { motorIndex = 0; }
  66029. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66030. };
  66031. /**
  66032. * Set the motor limits.
  66033. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66034. * @param {number} upperLimit the upper limit
  66035. * @param {number} lowerLimit lower limit
  66036. * @param {motorIndex} the motor's index, 0 or 1.
  66037. */
  66038. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66039. if (motorIndex === void 0) { motorIndex = 0; }
  66040. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66041. };
  66042. return Hinge2Joint;
  66043. }(MotorEnabledJoint));
  66044. BABYLON.Hinge2Joint = Hinge2Joint;
  66045. })(BABYLON || (BABYLON = {}));
  66046. //# sourceMappingURL=babylon.physicsJoint.js.map
  66047. var BABYLON;
  66048. (function (BABYLON) {
  66049. var PhysicsImpostor = /** @class */ (function () {
  66050. function PhysicsImpostor(object, type, _options, _scene) {
  66051. if (_options === void 0) { _options = { mass: 0 }; }
  66052. var _this = this;
  66053. this.object = object;
  66054. this.type = type;
  66055. this._options = _options;
  66056. this._scene = _scene;
  66057. this._bodyUpdateRequired = false;
  66058. this._onBeforePhysicsStepCallbacks = new Array();
  66059. this._onAfterPhysicsStepCallbacks = new Array();
  66060. this._onPhysicsCollideCallbacks = [];
  66061. this._deltaPosition = BABYLON.Vector3.Zero();
  66062. this._isDisposed = false;
  66063. //temp variables for parent rotation calculations
  66064. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66065. this._tmpQuat = new BABYLON.Quaternion();
  66066. this._tmpQuat2 = new BABYLON.Quaternion();
  66067. /**
  66068. * this function is executed by the physics engine.
  66069. */
  66070. this.beforeStep = function () {
  66071. if (!_this._physicsEngine) {
  66072. return;
  66073. }
  66074. _this.object.translate(_this._deltaPosition, -1);
  66075. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66076. _this.object.computeWorldMatrix(false);
  66077. if (_this.object.parent && _this.object.rotationQuaternion) {
  66078. _this.getParentsRotation();
  66079. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66080. }
  66081. else {
  66082. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66083. }
  66084. if (!_this._options.disableBidirectionalTransformation) {
  66085. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66086. }
  66087. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66088. func(_this);
  66089. });
  66090. };
  66091. /**
  66092. * this function is executed by the physics engine.
  66093. */
  66094. this.afterStep = function () {
  66095. if (!_this._physicsEngine) {
  66096. return;
  66097. }
  66098. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66099. func(_this);
  66100. });
  66101. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66102. // object has now its world rotation. needs to be converted to local.
  66103. if (_this.object.parent && _this.object.rotationQuaternion) {
  66104. _this.getParentsRotation();
  66105. _this._tmpQuat.conjugateInPlace();
  66106. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66107. }
  66108. // take the position set and make it the absolute position of this object.
  66109. _this.object.setAbsolutePosition(_this.object.position);
  66110. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66111. _this.object.translate(_this._deltaPosition, 1);
  66112. };
  66113. /**
  66114. * Legacy collision detection event support
  66115. */
  66116. this.onCollideEvent = null;
  66117. //event and body object due to cannon's event-based architecture.
  66118. this.onCollide = function (e) {
  66119. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66120. return;
  66121. }
  66122. if (!_this._physicsEngine) {
  66123. return;
  66124. }
  66125. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66126. if (otherImpostor) {
  66127. // Legacy collision detection event support
  66128. if (_this.onCollideEvent) {
  66129. _this.onCollideEvent(_this, otherImpostor);
  66130. }
  66131. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66132. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66133. }).forEach(function (obj) {
  66134. obj.callback(_this, otherImpostor);
  66135. });
  66136. }
  66137. };
  66138. //sanity check!
  66139. if (!this.object) {
  66140. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66141. return;
  66142. }
  66143. //legacy support for old syntax.
  66144. if (!this._scene && object.getScene) {
  66145. this._scene = object.getScene();
  66146. }
  66147. if (!this._scene) {
  66148. return;
  66149. }
  66150. this._physicsEngine = this._scene.getPhysicsEngine();
  66151. if (!this._physicsEngine) {
  66152. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66153. }
  66154. else {
  66155. //set the object's quaternion, if not set
  66156. if (!this.object.rotationQuaternion) {
  66157. if (this.object.rotation) {
  66158. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66159. }
  66160. else {
  66161. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66162. }
  66163. }
  66164. //default options params
  66165. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66166. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66167. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66168. this._joints = [];
  66169. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66170. if (!this.object.parent || this._options.ignoreParent) {
  66171. this._init();
  66172. }
  66173. else if (this.object.parent.physicsImpostor) {
  66174. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66175. }
  66176. }
  66177. }
  66178. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66179. get: function () {
  66180. return this._isDisposed;
  66181. },
  66182. enumerable: true,
  66183. configurable: true
  66184. });
  66185. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66186. get: function () {
  66187. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66188. },
  66189. set: function (value) {
  66190. this.setMass(value);
  66191. },
  66192. enumerable: true,
  66193. configurable: true
  66194. });
  66195. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66196. get: function () {
  66197. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66198. },
  66199. set: function (value) {
  66200. if (!this._physicsEngine) {
  66201. return;
  66202. }
  66203. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66204. },
  66205. enumerable: true,
  66206. configurable: true
  66207. });
  66208. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66209. get: function () {
  66210. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66211. },
  66212. set: function (value) {
  66213. if (!this._physicsEngine) {
  66214. return;
  66215. }
  66216. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66217. },
  66218. enumerable: true,
  66219. configurable: true
  66220. });
  66221. /**
  66222. * This function will completly initialize this impostor.
  66223. * It will create a new body - but only if this mesh has no parent.
  66224. * If it has, this impostor will not be used other than to define the impostor
  66225. * of the child mesh.
  66226. */
  66227. PhysicsImpostor.prototype._init = function () {
  66228. if (!this._physicsEngine) {
  66229. return;
  66230. }
  66231. this._physicsEngine.removeImpostor(this);
  66232. this.physicsBody = null;
  66233. this._parent = this._parent || this._getPhysicsParent();
  66234. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66235. this._physicsEngine.addImpostor(this);
  66236. }
  66237. };
  66238. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66239. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66240. var parentMesh = this.object.parent;
  66241. return parentMesh.physicsImpostor;
  66242. }
  66243. return null;
  66244. };
  66245. /**
  66246. * Should a new body be generated.
  66247. */
  66248. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66249. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66250. };
  66251. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66252. this.forceUpdate();
  66253. };
  66254. /**
  66255. * Force a regeneration of this or the parent's impostor's body.
  66256. * Use under cautious - This will remove all joints already implemented.
  66257. */
  66258. PhysicsImpostor.prototype.forceUpdate = function () {
  66259. this._init();
  66260. if (this.parent && !this._options.ignoreParent) {
  66261. this.parent.forceUpdate();
  66262. }
  66263. };
  66264. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66265. /*public get mesh(): AbstractMesh {
  66266. return this._mesh;
  66267. }*/
  66268. /**
  66269. * Gets the body that holds this impostor. Either its own, or its parent.
  66270. */
  66271. get: function () {
  66272. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66273. },
  66274. /**
  66275. * Set the physics body. Used mainly by the physics engine/plugin
  66276. */
  66277. set: function (physicsBody) {
  66278. if (this._physicsBody && this._physicsEngine) {
  66279. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66280. }
  66281. this._physicsBody = physicsBody;
  66282. this.resetUpdateFlags();
  66283. },
  66284. enumerable: true,
  66285. configurable: true
  66286. });
  66287. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66288. get: function () {
  66289. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66290. },
  66291. set: function (value) {
  66292. this._parent = value;
  66293. },
  66294. enumerable: true,
  66295. configurable: true
  66296. });
  66297. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66298. this._bodyUpdateRequired = false;
  66299. };
  66300. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66301. if (this.object.getBoundingInfo) {
  66302. var q = this.object.rotationQuaternion;
  66303. //reset rotation
  66304. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66305. //calculate the world matrix with no rotation
  66306. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66307. var boundingInfo = this.object.getBoundingInfo();
  66308. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66309. //bring back the rotation
  66310. this.object.rotationQuaternion = q;
  66311. //calculate the world matrix with the new rotation
  66312. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66313. return size;
  66314. }
  66315. else {
  66316. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66317. }
  66318. };
  66319. PhysicsImpostor.prototype.getObjectCenter = function () {
  66320. if (this.object.getBoundingInfo) {
  66321. var boundingInfo = this.object.getBoundingInfo();
  66322. return boundingInfo.boundingBox.centerWorld;
  66323. }
  66324. else {
  66325. return this.object.position;
  66326. }
  66327. };
  66328. /**
  66329. * Get a specific parametes from the options parameter.
  66330. */
  66331. PhysicsImpostor.prototype.getParam = function (paramName) {
  66332. return this._options[paramName];
  66333. };
  66334. /**
  66335. * Sets a specific parameter in the options given to the physics plugin
  66336. */
  66337. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66338. this._options[paramName] = value;
  66339. this._bodyUpdateRequired = true;
  66340. };
  66341. /**
  66342. * Specifically change the body's mass option. Won't recreate the physics body object
  66343. */
  66344. PhysicsImpostor.prototype.setMass = function (mass) {
  66345. if (this.getParam("mass") !== mass) {
  66346. this.setParam("mass", mass);
  66347. }
  66348. if (this._physicsEngine) {
  66349. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66350. }
  66351. };
  66352. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66353. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66354. };
  66355. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66356. if (this._physicsEngine) {
  66357. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66358. }
  66359. };
  66360. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66361. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66362. };
  66363. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66364. if (this._physicsEngine) {
  66365. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66366. }
  66367. };
  66368. /**
  66369. * Execute a function with the physics plugin native code.
  66370. * Provide a function the will have two variables - the world object and the physics body object.
  66371. */
  66372. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66373. if (this._physicsEngine) {
  66374. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66375. }
  66376. };
  66377. /**
  66378. * Register a function that will be executed before the physics world is stepping forward.
  66379. */
  66380. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66381. this._onBeforePhysicsStepCallbacks.push(func);
  66382. };
  66383. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66384. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66385. if (index > -1) {
  66386. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66387. }
  66388. else {
  66389. BABYLON.Tools.Warn("Function to remove was not found");
  66390. }
  66391. };
  66392. /**
  66393. * Register a function that will be executed after the physics step
  66394. */
  66395. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66396. this._onAfterPhysicsStepCallbacks.push(func);
  66397. };
  66398. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66399. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66400. if (index > -1) {
  66401. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66402. }
  66403. else {
  66404. BABYLON.Tools.Warn("Function to remove was not found");
  66405. }
  66406. };
  66407. /**
  66408. * register a function that will be executed when this impostor collides against a different body.
  66409. */
  66410. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66411. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66412. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66413. };
  66414. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66415. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66416. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66417. if (index > -1) {
  66418. this._onPhysicsCollideCallbacks.splice(index, 1);
  66419. }
  66420. else {
  66421. BABYLON.Tools.Warn("Function to remove was not found");
  66422. }
  66423. };
  66424. PhysicsImpostor.prototype.getParentsRotation = function () {
  66425. var parent = this.object.parent;
  66426. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66427. while (parent) {
  66428. if (parent.rotationQuaternion) {
  66429. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66430. }
  66431. else {
  66432. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66433. }
  66434. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66435. parent = parent.parent;
  66436. }
  66437. return this._tmpQuat;
  66438. };
  66439. /**
  66440. * Apply a force
  66441. */
  66442. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66443. if (this._physicsEngine) {
  66444. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66445. }
  66446. return this;
  66447. };
  66448. /**
  66449. * Apply an impulse
  66450. */
  66451. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66452. if (this._physicsEngine) {
  66453. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66454. }
  66455. return this;
  66456. };
  66457. /**
  66458. * A help function to create a joint.
  66459. */
  66460. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66461. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66462. this.addJoint(otherImpostor, joint);
  66463. return this;
  66464. };
  66465. /**
  66466. * Add a joint to this impostor with a different impostor.
  66467. */
  66468. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66469. this._joints.push({
  66470. otherImpostor: otherImpostor,
  66471. joint: joint
  66472. });
  66473. if (this._physicsEngine) {
  66474. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66475. }
  66476. return this;
  66477. };
  66478. /**
  66479. * Will keep this body still, in a sleep mode.
  66480. */
  66481. PhysicsImpostor.prototype.sleep = function () {
  66482. if (this._physicsEngine) {
  66483. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66484. }
  66485. return this;
  66486. };
  66487. /**
  66488. * Wake the body up.
  66489. */
  66490. PhysicsImpostor.prototype.wakeUp = function () {
  66491. if (this._physicsEngine) {
  66492. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66493. }
  66494. return this;
  66495. };
  66496. PhysicsImpostor.prototype.clone = function (newObject) {
  66497. if (!newObject)
  66498. return null;
  66499. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66500. };
  66501. PhysicsImpostor.prototype.dispose = function () {
  66502. var _this = this;
  66503. //no dispose if no physics engine is available.
  66504. if (!this._physicsEngine) {
  66505. return;
  66506. }
  66507. this._joints.forEach(function (j) {
  66508. if (_this._physicsEngine) {
  66509. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66510. }
  66511. });
  66512. //dispose the physics body
  66513. this._physicsEngine.removeImpostor(this);
  66514. if (this.parent) {
  66515. this.parent.forceUpdate();
  66516. }
  66517. else {
  66518. /*this._object.getChildMeshes().forEach(function(mesh) {
  66519. if (mesh.physicsImpostor) {
  66520. if (disposeChildren) {
  66521. mesh.physicsImpostor.dispose();
  66522. mesh.physicsImpostor = null;
  66523. }
  66524. }
  66525. })*/
  66526. }
  66527. this._isDisposed = true;
  66528. };
  66529. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66530. this._deltaPosition.copyFrom(position);
  66531. };
  66532. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66533. if (!this._deltaRotation) {
  66534. this._deltaRotation = new BABYLON.Quaternion();
  66535. }
  66536. this._deltaRotation.copyFrom(rotation);
  66537. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66538. };
  66539. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66540. if (this._physicsEngine) {
  66541. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66542. }
  66543. return this;
  66544. };
  66545. PhysicsImpostor.prototype.getRadius = function () {
  66546. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66547. };
  66548. /**
  66549. * Sync a bone with this impostor
  66550. * @param bone The bone to sync to the impostor.
  66551. * @param boneMesh The mesh that the bone is influencing.
  66552. * @param jointPivot The pivot of the joint / bone in local space.
  66553. * @param distToJoint Optional distance from the impostor to the joint.
  66554. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66555. */
  66556. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66557. var tempVec = PhysicsImpostor._tmpVecs[0];
  66558. var mesh = this.object;
  66559. if (mesh.rotationQuaternion) {
  66560. if (adjustRotation) {
  66561. var tempQuat = PhysicsImpostor._tmpQuat;
  66562. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66563. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66564. }
  66565. else {
  66566. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66567. }
  66568. }
  66569. tempVec.x = 0;
  66570. tempVec.y = 0;
  66571. tempVec.z = 0;
  66572. if (jointPivot) {
  66573. tempVec.x = jointPivot.x;
  66574. tempVec.y = jointPivot.y;
  66575. tempVec.z = jointPivot.z;
  66576. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66577. if (distToJoint === undefined || distToJoint === null) {
  66578. distToJoint = jointPivot.length();
  66579. }
  66580. tempVec.x *= distToJoint;
  66581. tempVec.y *= distToJoint;
  66582. tempVec.z *= distToJoint;
  66583. }
  66584. if (bone.getParent()) {
  66585. tempVec.addInPlace(mesh.getAbsolutePosition());
  66586. bone.setAbsolutePosition(tempVec, boneMesh);
  66587. }
  66588. else {
  66589. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66590. boneMesh.position.x -= tempVec.x;
  66591. boneMesh.position.y -= tempVec.y;
  66592. boneMesh.position.z -= tempVec.z;
  66593. }
  66594. };
  66595. /**
  66596. * Sync impostor to a bone
  66597. * @param bone The bone that the impostor will be synced to.
  66598. * @param boneMesh The mesh that the bone is influencing.
  66599. * @param jointPivot The pivot of the joint / bone in local space.
  66600. * @param distToJoint Optional distance from the impostor to the joint.
  66601. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66602. * @param boneAxis Optional vector3 axis the bone is aligned with
  66603. */
  66604. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66605. var mesh = this.object;
  66606. if (mesh.rotationQuaternion) {
  66607. if (adjustRotation) {
  66608. var tempQuat = PhysicsImpostor._tmpQuat;
  66609. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66610. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66611. }
  66612. else {
  66613. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66614. }
  66615. }
  66616. var pos = PhysicsImpostor._tmpVecs[0];
  66617. var boneDir = PhysicsImpostor._tmpVecs[1];
  66618. if (!boneAxis) {
  66619. boneAxis = PhysicsImpostor._tmpVecs[2];
  66620. boneAxis.x = 0;
  66621. boneAxis.y = 1;
  66622. boneAxis.z = 0;
  66623. }
  66624. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66625. bone.getAbsolutePositionToRef(boneMesh, pos);
  66626. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66627. distToJoint = jointPivot.length();
  66628. }
  66629. if (distToJoint !== undefined && distToJoint !== null) {
  66630. pos.x += boneDir.x * distToJoint;
  66631. pos.y += boneDir.y * distToJoint;
  66632. pos.z += boneDir.z * distToJoint;
  66633. }
  66634. mesh.setAbsolutePosition(pos);
  66635. };
  66636. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66637. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66638. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66639. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66640. //Impostor types
  66641. PhysicsImpostor.NoImpostor = 0;
  66642. PhysicsImpostor.SphereImpostor = 1;
  66643. PhysicsImpostor.BoxImpostor = 2;
  66644. PhysicsImpostor.PlaneImpostor = 3;
  66645. PhysicsImpostor.MeshImpostor = 4;
  66646. PhysicsImpostor.CylinderImpostor = 7;
  66647. PhysicsImpostor.ParticleImpostor = 8;
  66648. PhysicsImpostor.HeightmapImpostor = 9;
  66649. return PhysicsImpostor;
  66650. }());
  66651. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66652. })(BABYLON || (BABYLON = {}));
  66653. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66654. var BABYLON;
  66655. (function (BABYLON) {
  66656. var PhysicsEngine = /** @class */ (function () {
  66657. function PhysicsEngine(gravity, _physicsPlugin) {
  66658. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66659. this._physicsPlugin = _physicsPlugin;
  66660. //new methods and parameters
  66661. this._impostors = [];
  66662. this._joints = [];
  66663. if (!this._physicsPlugin.isSupported()) {
  66664. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66665. + "Please make sure it is included.");
  66666. }
  66667. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66668. this.setGravity(gravity);
  66669. this.setTimeStep();
  66670. }
  66671. PhysicsEngine.prototype.setGravity = function (gravity) {
  66672. this.gravity = gravity;
  66673. this._physicsPlugin.setGravity(this.gravity);
  66674. };
  66675. /**
  66676. * Set the time step of the physics engine.
  66677. * default is 1/60.
  66678. * To slow it down, enter 1/600 for example.
  66679. * To speed it up, 1/30
  66680. * @param {number} newTimeStep the new timestep to apply to this world.
  66681. */
  66682. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66683. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66684. this._physicsPlugin.setTimeStep(newTimeStep);
  66685. };
  66686. /**
  66687. * Get the time step of the physics engine.
  66688. */
  66689. PhysicsEngine.prototype.getTimeStep = function () {
  66690. return this._physicsPlugin.getTimeStep();
  66691. };
  66692. PhysicsEngine.prototype.dispose = function () {
  66693. this._impostors.forEach(function (impostor) {
  66694. impostor.dispose();
  66695. });
  66696. this._physicsPlugin.dispose();
  66697. };
  66698. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66699. return this._physicsPlugin.name;
  66700. };
  66701. /**
  66702. * Adding a new impostor for the impostor tracking.
  66703. * This will be done by the impostor itself.
  66704. * @param {PhysicsImpostor} impostor the impostor to add
  66705. */
  66706. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66707. impostor.uniqueId = this._impostors.push(impostor);
  66708. //if no parent, generate the body
  66709. if (!impostor.parent) {
  66710. this._physicsPlugin.generatePhysicsBody(impostor);
  66711. }
  66712. };
  66713. /**
  66714. * Remove an impostor from the engine.
  66715. * This impostor and its mesh will not longer be updated by the physics engine.
  66716. * @param {PhysicsImpostor} impostor the impostor to remove
  66717. */
  66718. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66719. var index = this._impostors.indexOf(impostor);
  66720. if (index > -1) {
  66721. var removed = this._impostors.splice(index, 1);
  66722. //Is it needed?
  66723. if (removed.length) {
  66724. //this will also remove it from the world.
  66725. removed[0].physicsBody = null;
  66726. }
  66727. }
  66728. };
  66729. /**
  66730. * Add a joint to the physics engine
  66731. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66732. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66733. * @param {PhysicsJoint} the joint that will connect both impostors.
  66734. */
  66735. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66736. var impostorJoint = {
  66737. mainImpostor: mainImpostor,
  66738. connectedImpostor: connectedImpostor,
  66739. joint: joint
  66740. };
  66741. joint.physicsPlugin = this._physicsPlugin;
  66742. this._joints.push(impostorJoint);
  66743. this._physicsPlugin.generateJoint(impostorJoint);
  66744. };
  66745. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66746. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66747. return (impostorJoint.connectedImpostor === connectedImpostor
  66748. && impostorJoint.joint === joint
  66749. && impostorJoint.mainImpostor === mainImpostor);
  66750. });
  66751. if (matchingJoints.length) {
  66752. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66753. //TODO remove it from the list as well
  66754. }
  66755. };
  66756. /**
  66757. * Called by the scene. no need to call it.
  66758. */
  66759. PhysicsEngine.prototype._step = function (delta) {
  66760. var _this = this;
  66761. //check if any mesh has no body / requires an update
  66762. this._impostors.forEach(function (impostor) {
  66763. if (impostor.isBodyInitRequired()) {
  66764. _this._physicsPlugin.generatePhysicsBody(impostor);
  66765. }
  66766. });
  66767. if (delta > 0.1) {
  66768. delta = 0.1;
  66769. }
  66770. else if (delta <= 0) {
  66771. delta = 1.0 / 60.0;
  66772. }
  66773. this._physicsPlugin.executeStep(delta, this._impostors);
  66774. };
  66775. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66776. return this._physicsPlugin;
  66777. };
  66778. PhysicsEngine.prototype.getImpostors = function () {
  66779. return this._impostors;
  66780. };
  66781. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66782. for (var i = 0; i < this._impostors.length; ++i) {
  66783. if (this._impostors[i].object === object) {
  66784. return this._impostors[i];
  66785. }
  66786. }
  66787. return null;
  66788. };
  66789. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66790. for (var i = 0; i < this._impostors.length; ++i) {
  66791. if (this._impostors[i].physicsBody === body) {
  66792. return this._impostors[i];
  66793. }
  66794. }
  66795. return null;
  66796. };
  66797. // Statics
  66798. PhysicsEngine.Epsilon = 0.001;
  66799. return PhysicsEngine;
  66800. }());
  66801. BABYLON.PhysicsEngine = PhysicsEngine;
  66802. })(BABYLON || (BABYLON = {}));
  66803. //# sourceMappingURL=babylon.physicsEngine.js.map
  66804. var BABYLON;
  66805. (function (BABYLON) {
  66806. /**
  66807. * The strenght of the force in correspondence to the distance of the affected object
  66808. */
  66809. var PhysicsRadialImpulseFalloff;
  66810. (function (PhysicsRadialImpulseFalloff) {
  66811. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  66812. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  66813. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  66814. /**
  66815. * The strenght of the force in correspondence to the distance of the affected object
  66816. */
  66817. var PhysicsUpdraftMode;
  66818. (function (PhysicsUpdraftMode) {
  66819. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  66820. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  66821. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  66822. var PhysicsHelper = /** @class */ (function () {
  66823. function PhysicsHelper(scene) {
  66824. this._scene = scene;
  66825. this._physicsEngine = this._scene.getPhysicsEngine();
  66826. if (!this._physicsEngine) {
  66827. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  66828. }
  66829. }
  66830. /**
  66831. * @param {Vector3} origin the origin of the explosion
  66832. * @param {number} radius the explosion radius
  66833. * @param {number} strength the explosion strength
  66834. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66835. */
  66836. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  66837. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66838. if (!this._physicsEngine) {
  66839. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  66840. return null;
  66841. }
  66842. var impostors = this._physicsEngine.getImpostors();
  66843. if (impostors.length === 0) {
  66844. return null;
  66845. }
  66846. var event = new PhysicsRadialExplosionEvent(this._scene);
  66847. impostors.forEach(function (impostor) {
  66848. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66849. if (!impostorForceAndContactPoint) {
  66850. return;
  66851. }
  66852. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66853. });
  66854. event.dispose(false);
  66855. return event;
  66856. };
  66857. /**
  66858. * @param {Vector3} origin the origin of the explosion
  66859. * @param {number} radius the explosion radius
  66860. * @param {number} strength the explosion strength
  66861. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66862. */
  66863. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  66864. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66865. if (!this._physicsEngine) {
  66866. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66867. return null;
  66868. }
  66869. var impostors = this._physicsEngine.getImpostors();
  66870. if (impostors.length === 0) {
  66871. return null;
  66872. }
  66873. var event = new PhysicsRadialExplosionEvent(this._scene);
  66874. impostors.forEach(function (impostor) {
  66875. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66876. if (!impostorForceAndContactPoint) {
  66877. return;
  66878. }
  66879. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66880. });
  66881. event.dispose(false);
  66882. return event;
  66883. };
  66884. /**
  66885. * @param {Vector3} origin the origin of the explosion
  66886. * @param {number} radius the explosion radius
  66887. * @param {number} strength the explosion strength
  66888. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66889. */
  66890. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  66891. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66892. if (!this._physicsEngine) {
  66893. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66894. return null;
  66895. }
  66896. var impostors = this._physicsEngine.getImpostors();
  66897. if (impostors.length === 0) {
  66898. return null;
  66899. }
  66900. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  66901. event.dispose(false);
  66902. return event;
  66903. };
  66904. /**
  66905. * @param {Vector3} origin the origin of the updraft
  66906. * @param {number} radius the radius of the updraft
  66907. * @param {number} strength the strength of the updraft
  66908. * @param {number} height the height of the updraft
  66909. */
  66910. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  66911. if (!this._physicsEngine) {
  66912. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66913. return null;
  66914. }
  66915. if (this._physicsEngine.getImpostors().length === 0) {
  66916. return null;
  66917. }
  66918. var event = new PhysicsUpdraftEvent(this._physicsEngine, this._scene, origin, radius, strength, height, updraftMode);
  66919. event.dispose(false);
  66920. return event;
  66921. };
  66922. return PhysicsHelper;
  66923. }());
  66924. BABYLON.PhysicsHelper = PhysicsHelper;
  66925. /***** Radial explosion *****/
  66926. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  66927. function PhysicsRadialExplosionEvent(scene) {
  66928. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  66929. this._rays = [];
  66930. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  66931. this._scene = scene;
  66932. }
  66933. /**
  66934. * Returns the data related to the radial explosion event (sphere & rays).
  66935. * @returns {PhysicsRadialExplosionEventData}
  66936. */
  66937. PhysicsRadialExplosionEvent.prototype.getData = function () {
  66938. this._dataFetched = true;
  66939. return {
  66940. sphere: this._sphere,
  66941. rays: this._rays,
  66942. };
  66943. };
  66944. /**
  66945. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  66946. * @param impostor
  66947. * @param {Vector3} origin the origin of the explosion
  66948. * @param {number} radius the explosion radius
  66949. * @param {number} strength the explosion strength
  66950. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  66951. * @returns {Nullable<PhysicsForceAndContactPoint>}
  66952. */
  66953. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  66954. if (impostor.mass === 0) {
  66955. return null;
  66956. }
  66957. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  66958. return null;
  66959. }
  66960. var impostorObject = impostor.object;
  66961. var impostorObjectCenter = impostor.getObjectCenter();
  66962. var direction = impostorObjectCenter.subtract(origin);
  66963. var ray = new BABYLON.Ray(origin, direction, radius);
  66964. this._rays.push(ray);
  66965. var hit = ray.intersectsMesh(impostorObject);
  66966. var contactPoint = hit.pickedPoint;
  66967. if (!contactPoint) {
  66968. return null;
  66969. }
  66970. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  66971. if (distanceFromOrigin > radius) {
  66972. return null;
  66973. }
  66974. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  66975. ? strength
  66976. : strength * (1 - (distanceFromOrigin / radius));
  66977. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  66978. return { force: force, contactPoint: contactPoint };
  66979. };
  66980. /**
  66981. * Disposes the sphere.
  66982. * @param {bolean} force
  66983. */
  66984. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  66985. var _this = this;
  66986. if (force === void 0) { force = true; }
  66987. if (force) {
  66988. this._sphere.dispose();
  66989. }
  66990. else {
  66991. setTimeout(function () {
  66992. if (!_this._dataFetched) {
  66993. _this._sphere.dispose();
  66994. }
  66995. }, 0);
  66996. }
  66997. };
  66998. /*** Helpers ***/
  66999. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67000. if (!this._sphere) {
  67001. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67002. this._sphere.isVisible = false;
  67003. }
  67004. };
  67005. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67006. var impostorObject = impostor.object;
  67007. this._prepareSphere();
  67008. this._sphere.position = origin;
  67009. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67010. this._sphere._updateBoundingInfo();
  67011. this._sphere.computeWorldMatrix(true);
  67012. return this._sphere.intersectsMesh(impostorObject, true);
  67013. };
  67014. return PhysicsRadialExplosionEvent;
  67015. }());
  67016. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67017. /***** Gravitational Field *****/
  67018. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67019. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67020. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67021. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67022. this._physicsHelper = physicsHelper;
  67023. this._scene = scene;
  67024. this._origin = origin;
  67025. this._radius = radius;
  67026. this._strength = strength;
  67027. this._falloff = falloff;
  67028. this._tickCallback = this._tick.bind(this);
  67029. }
  67030. /**
  67031. * Returns the data related to the gravitational field event (sphere).
  67032. * @returns {PhysicsGravitationalFieldEventData}
  67033. */
  67034. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67035. this._dataFetched = true;
  67036. return {
  67037. sphere: this._sphere,
  67038. };
  67039. };
  67040. /**
  67041. * Enables the gravitational field.
  67042. */
  67043. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67044. this._tickCallback.call(this);
  67045. this._scene.registerBeforeRender(this._tickCallback);
  67046. };
  67047. /**
  67048. * Disables the gravitational field.
  67049. */
  67050. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67051. this._scene.unregisterBeforeRender(this._tickCallback);
  67052. };
  67053. /**
  67054. * Disposes the sphere.
  67055. * @param {bolean} force
  67056. */
  67057. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67058. var _this = this;
  67059. if (force === void 0) { force = true; }
  67060. if (force) {
  67061. this._sphere.dispose();
  67062. }
  67063. else {
  67064. setTimeout(function () {
  67065. if (!_this._dataFetched) {
  67066. _this._sphere.dispose();
  67067. }
  67068. }, 0);
  67069. }
  67070. };
  67071. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67072. // Since the params won't change, we fetch the event only once
  67073. if (this._sphere) {
  67074. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67075. }
  67076. else {
  67077. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67078. if (radialExplosionEvent) {
  67079. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67080. }
  67081. }
  67082. };
  67083. return PhysicsGravitationalFieldEvent;
  67084. }());
  67085. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67086. /***** Updraft *****/
  67087. var PhysicsUpdraftEvent = /** @class */ (function () {
  67088. function PhysicsUpdraftEvent(physicsEngine, scene, origin, radius, strength, height, updraftMode) {
  67089. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67090. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67091. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67092. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67093. this._physicsEngine = physicsEngine;
  67094. this._scene = scene;
  67095. this._origin = origin;
  67096. this._radius = radius;
  67097. this._strength = strength;
  67098. this._height = height;
  67099. this._updraftMode = updraftMode;
  67100. // TODO: for this._cylinderPosition & this._originTop, take rotation into account
  67101. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67102. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67103. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67104. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67105. }
  67106. this._tickCallback = this._tick.bind(this);
  67107. }
  67108. /**
  67109. * Returns the data related to the updraft event (cylinder).
  67110. * @returns {PhysicsGravitationalFieldEventData}
  67111. */
  67112. PhysicsUpdraftEvent.prototype.getData = function () {
  67113. this._dataFetched = true;
  67114. return {
  67115. cylinder: this._cylinder,
  67116. };
  67117. };
  67118. /**
  67119. * Enables the updraft.
  67120. */
  67121. PhysicsUpdraftEvent.prototype.enable = function () {
  67122. this._tickCallback.call(this);
  67123. this._scene.registerBeforeRender(this._tickCallback);
  67124. };
  67125. /**
  67126. * Disables the cortex.
  67127. */
  67128. PhysicsUpdraftEvent.prototype.disable = function () {
  67129. this._scene.unregisterBeforeRender(this._tickCallback);
  67130. };
  67131. /**
  67132. * Disposes the sphere.
  67133. * @param {bolean} force
  67134. */
  67135. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67136. var _this = this;
  67137. if (force === void 0) { force = true; }
  67138. if (force) {
  67139. this._cylinder.dispose();
  67140. }
  67141. else {
  67142. setTimeout(function () {
  67143. if (!_this._dataFetched) {
  67144. _this._cylinder.dispose();
  67145. }
  67146. }, 0);
  67147. }
  67148. };
  67149. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67150. if (impostor.mass === 0) {
  67151. return null;
  67152. }
  67153. if (!this._intersectsWithCylinder(impostor)) {
  67154. return null;
  67155. }
  67156. var impostorObjectCenter = impostor.getObjectCenter();
  67157. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67158. var direction = this._originDirection;
  67159. }
  67160. else {
  67161. var direction = impostorObjectCenter.subtract(this._originTop);
  67162. }
  67163. var multiplier = this._strength * -1;
  67164. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67165. return { force: force, contactPoint: impostorObjectCenter };
  67166. };
  67167. PhysicsUpdraftEvent.prototype._tick = function () {
  67168. var _this = this;
  67169. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67170. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67171. if (!impostorForceAndContactPoint) {
  67172. return;
  67173. }
  67174. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67175. });
  67176. };
  67177. /*** Helpers ***/
  67178. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67179. if (!this._cylinder) {
  67180. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67181. height: this._height,
  67182. diameter: this._radius * 2,
  67183. }, this._scene);
  67184. this._cylinder.isVisible = false;
  67185. }
  67186. };
  67187. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67188. var impostorObject = impostor.object;
  67189. this._prepareCylinder();
  67190. this._cylinder.position = this._cylinderPosition;
  67191. return this._cylinder.intersectsMesh(impostorObject, true);
  67192. };
  67193. return PhysicsUpdraftEvent;
  67194. }());
  67195. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67196. })(BABYLON || (BABYLON = {}));
  67197. //# sourceMappingURL=babylon.physicsHelper.js.map
  67198. var BABYLON;
  67199. (function (BABYLON) {
  67200. var CannonJSPlugin = /** @class */ (function () {
  67201. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  67202. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  67203. if (iterations === void 0) { iterations = 10; }
  67204. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  67205. this.name = "CannonJSPlugin";
  67206. this._physicsMaterials = new Array();
  67207. this._fixedTimeStep = 1 / 60;
  67208. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  67209. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  67210. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  67211. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  67212. this._tmpPosition = BABYLON.Vector3.Zero();
  67213. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  67214. this._tmpUnityRotation = new BABYLON.Quaternion();
  67215. if (!this.isSupported()) {
  67216. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  67217. return;
  67218. }
  67219. this.world = new this.BJSCANNON.World();
  67220. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  67221. this.world.solver.iterations = iterations;
  67222. }
  67223. CannonJSPlugin.prototype.setGravity = function (gravity) {
  67224. this.world.gravity.copy(gravity);
  67225. };
  67226. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  67227. this._fixedTimeStep = timeStep;
  67228. };
  67229. CannonJSPlugin.prototype.getTimeStep = function () {
  67230. return this._fixedTimeStep;
  67231. };
  67232. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  67233. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  67234. };
  67235. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67236. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67237. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67238. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  67239. };
  67240. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67241. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67242. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67243. impostor.physicsBody.applyForce(impulse, worldPoint);
  67244. };
  67245. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67246. //parent-child relationship. Does this impostor has a parent impostor?
  67247. if (impostor.parent) {
  67248. if (impostor.physicsBody) {
  67249. this.removePhysicsBody(impostor);
  67250. //TODO is that needed?
  67251. impostor.forceUpdate();
  67252. }
  67253. return;
  67254. }
  67255. //should a new body be created for this impostor?
  67256. if (impostor.isBodyInitRequired()) {
  67257. var shape = this._createShape(impostor);
  67258. //unregister events, if body is being changed
  67259. var oldBody = impostor.physicsBody;
  67260. if (oldBody) {
  67261. this.removePhysicsBody(impostor);
  67262. }
  67263. //create the body and material
  67264. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  67265. var bodyCreationObject = {
  67266. mass: impostor.getParam("mass"),
  67267. material: material
  67268. };
  67269. // A simple extend, in case native options were used.
  67270. var nativeOptions = impostor.getParam("nativeOptions");
  67271. for (var key in nativeOptions) {
  67272. if (nativeOptions.hasOwnProperty(key)) {
  67273. bodyCreationObject[key] = nativeOptions[key];
  67274. }
  67275. }
  67276. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  67277. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  67278. this.world.addEventListener("preStep", impostor.beforeStep);
  67279. this.world.addEventListener("postStep", impostor.afterStep);
  67280. impostor.physicsBody.addShape(shape);
  67281. this.world.add(impostor.physicsBody);
  67282. //try to keep the body moving in the right direction by taking old properties.
  67283. //Should be tested!
  67284. if (oldBody) {
  67285. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  67286. impostor.physicsBody[param].copy(oldBody[param]);
  67287. });
  67288. }
  67289. this._processChildMeshes(impostor);
  67290. }
  67291. //now update the body's transformation
  67292. this._updatePhysicsBodyTransformation(impostor);
  67293. };
  67294. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  67295. var _this = this;
  67296. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  67297. var currentRotation = mainImpostor.object.rotationQuaternion;
  67298. if (meshChildren.length) {
  67299. var processMesh = function (localPosition, mesh) {
  67300. if (!currentRotation || !mesh.rotationQuaternion) {
  67301. return;
  67302. }
  67303. var childImpostor = mesh.getPhysicsImpostor();
  67304. if (childImpostor) {
  67305. var parent = childImpostor.parent;
  67306. if (parent !== mainImpostor) {
  67307. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67308. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67309. if (childImpostor.physicsBody) {
  67310. _this.removePhysicsBody(childImpostor);
  67311. childImpostor.physicsBody = null;
  67312. }
  67313. childImpostor.parent = mainImpostor;
  67314. childImpostor.resetUpdateFlags();
  67315. 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));
  67316. //Add the mass of the children.
  67317. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67318. }
  67319. }
  67320. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67321. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67322. };
  67323. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67324. }
  67325. };
  67326. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67327. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67328. this.world.removeEventListener("preStep", impostor.beforeStep);
  67329. this.world.removeEventListener("postStep", impostor.afterStep);
  67330. this.world.remove(impostor.physicsBody);
  67331. };
  67332. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67333. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67334. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67335. if (!mainBody || !connectedBody) {
  67336. return;
  67337. }
  67338. var constraint;
  67339. var jointData = impostorJoint.joint.jointData;
  67340. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67341. var constraintData = {
  67342. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67343. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67344. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67345. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67346. maxForce: jointData.nativeParams.maxForce,
  67347. collideConnected: !!jointData.collision
  67348. };
  67349. switch (impostorJoint.joint.type) {
  67350. case BABYLON.PhysicsJoint.HingeJoint:
  67351. case BABYLON.PhysicsJoint.Hinge2Joint:
  67352. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67353. break;
  67354. case BABYLON.PhysicsJoint.DistanceJoint:
  67355. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67356. break;
  67357. case BABYLON.PhysicsJoint.SpringJoint:
  67358. var springData = jointData;
  67359. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67360. restLength: springData.length,
  67361. stiffness: springData.stiffness,
  67362. damping: springData.damping,
  67363. localAnchorA: constraintData.pivotA,
  67364. localAnchorB: constraintData.pivotB
  67365. });
  67366. break;
  67367. case BABYLON.PhysicsJoint.LockJoint:
  67368. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67369. break;
  67370. case BABYLON.PhysicsJoint.PointToPointJoint:
  67371. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67372. default:
  67373. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67374. break;
  67375. }
  67376. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67377. constraint.collideConnected = !!jointData.collision;
  67378. impostorJoint.joint.physicsJoint = constraint;
  67379. //don't add spring as constraint, as it is not one.
  67380. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67381. this.world.addConstraint(constraint);
  67382. }
  67383. else {
  67384. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67385. constraint.applyForce();
  67386. });
  67387. }
  67388. };
  67389. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67390. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67391. };
  67392. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67393. var index;
  67394. var mat;
  67395. for (index = 0; index < this._physicsMaterials.length; index++) {
  67396. mat = this._physicsMaterials[index];
  67397. if (mat.friction === friction && mat.restitution === restitution) {
  67398. return mat;
  67399. }
  67400. }
  67401. var currentMat = new this.BJSCANNON.Material(name);
  67402. currentMat.friction = friction;
  67403. currentMat.restitution = restitution;
  67404. this._physicsMaterials.push(currentMat);
  67405. return currentMat;
  67406. };
  67407. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67408. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67409. };
  67410. CannonJSPlugin.prototype._createShape = function (impostor) {
  67411. var object = impostor.object;
  67412. var returnValue;
  67413. var extendSize = impostor.getObjectExtendSize();
  67414. switch (impostor.type) {
  67415. case BABYLON.PhysicsImpostor.SphereImpostor:
  67416. var radiusX = extendSize.x;
  67417. var radiusY = extendSize.y;
  67418. var radiusZ = extendSize.z;
  67419. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67420. break;
  67421. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67422. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67423. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67424. break;
  67425. case BABYLON.PhysicsImpostor.BoxImpostor:
  67426. var box = extendSize.scale(0.5);
  67427. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67428. break;
  67429. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67430. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67431. returnValue = new this.BJSCANNON.Plane();
  67432. break;
  67433. case BABYLON.PhysicsImpostor.MeshImpostor:
  67434. // should transform the vertex data to world coordinates!!
  67435. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67436. var rawFaces = object.getIndices ? object.getIndices() : [];
  67437. if (!rawVerts)
  67438. return;
  67439. // get only scale! so the object could transform correctly.
  67440. var oldPosition = object.position.clone();
  67441. var oldRotation = object.rotation && object.rotation.clone();
  67442. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67443. object.position.copyFromFloats(0, 0, 0);
  67444. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67445. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67446. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67447. var transform = object.computeWorldMatrix(true);
  67448. // convert rawVerts to object space
  67449. var temp = new Array();
  67450. var index;
  67451. for (index = 0; index < rawVerts.length; index += 3) {
  67452. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67453. }
  67454. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67455. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67456. //now set back the transformation!
  67457. object.position.copyFrom(oldPosition);
  67458. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67459. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67460. break;
  67461. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67462. var oldPosition2 = object.position.clone();
  67463. var oldRotation2 = object.rotation && object.rotation.clone();
  67464. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  67465. object.position.copyFromFloats(0, 0, 0);
  67466. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67467. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67468. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67469. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  67470. returnValue = this._createHeightmap(object);
  67471. object.position.copyFrom(oldPosition2);
  67472. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  67473. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  67474. object.computeWorldMatrix(true);
  67475. break;
  67476. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67477. returnValue = new this.BJSCANNON.Particle();
  67478. break;
  67479. }
  67480. return returnValue;
  67481. };
  67482. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  67483. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67484. var transform = object.computeWorldMatrix(true);
  67485. // convert rawVerts to object space
  67486. var temp = new Array();
  67487. var index;
  67488. for (index = 0; index < pos.length; index += 3) {
  67489. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  67490. }
  67491. pos = temp;
  67492. var matrix = new Array();
  67493. //For now pointDepth will not be used and will be automatically calculated.
  67494. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  67495. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  67496. var boundingInfo = object.getBoundingInfo();
  67497. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  67498. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  67499. var elementSize = dim * 2 / arraySize;
  67500. for (var i = 0; i < pos.length; i = i + 3) {
  67501. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  67502. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  67503. var y = -pos[i + 2] + minY;
  67504. if (!matrix[x]) {
  67505. matrix[x] = [];
  67506. }
  67507. if (!matrix[x][z]) {
  67508. matrix[x][z] = y;
  67509. }
  67510. matrix[x][z] = Math.max(y, matrix[x][z]);
  67511. }
  67512. for (var x = 0; x <= arraySize; ++x) {
  67513. if (!matrix[x]) {
  67514. var loc = 1;
  67515. while (!matrix[(x + loc) % arraySize]) {
  67516. loc++;
  67517. }
  67518. matrix[x] = matrix[(x + loc) % arraySize].slice();
  67519. //console.log("missing x", x);
  67520. }
  67521. for (var z = 0; z <= arraySize; ++z) {
  67522. if (!matrix[x][z]) {
  67523. var loc = 1;
  67524. var newValue;
  67525. while (newValue === undefined) {
  67526. newValue = matrix[x][(z + loc++) % arraySize];
  67527. }
  67528. matrix[x][z] = newValue;
  67529. }
  67530. }
  67531. }
  67532. var shape = new this.BJSCANNON.Heightfield(matrix, {
  67533. elementSize: elementSize
  67534. });
  67535. //For future reference, needed for body transformation
  67536. shape.minY = minY;
  67537. return shape;
  67538. };
  67539. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  67540. var object = impostor.object;
  67541. //make sure it is updated...
  67542. object.computeWorldMatrix && object.computeWorldMatrix(true);
  67543. // The delta between the mesh position and the mesh bounding box center
  67544. var bInfo = object.getBoundingInfo();
  67545. if (!bInfo)
  67546. return;
  67547. var center = impostor.getObjectCenter();
  67548. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  67549. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  67550. this._tmpPosition.copyFrom(center);
  67551. var quaternion = object.rotationQuaternion;
  67552. if (!quaternion) {
  67553. return;
  67554. }
  67555. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  67556. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  67557. //-90 DEG in X, precalculated
  67558. quaternion = quaternion.multiply(this._minus90X);
  67559. //Invert! (Precalculated, 90 deg in X)
  67560. //No need to clone. this will never change.
  67561. impostor.setDeltaRotation(this._plus90X);
  67562. }
  67563. //If it is a heightfield, if should be centered.
  67564. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  67565. var mesh = object;
  67566. var boundingInfo = mesh.getBoundingInfo();
  67567. //calculate the correct body position:
  67568. var rotationQuaternion = mesh.rotationQuaternion;
  67569. mesh.rotationQuaternion = this._tmpUnityRotation;
  67570. mesh.computeWorldMatrix(true);
  67571. //get original center with no rotation
  67572. var c = center.clone();
  67573. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  67574. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  67575. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  67576. mesh.setPivotMatrix(p);
  67577. mesh.computeWorldMatrix(true);
  67578. //calculate the translation
  67579. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  67580. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  67581. //add it inverted to the delta
  67582. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  67583. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  67584. //rotation is back
  67585. mesh.rotationQuaternion = rotationQuaternion;
  67586. mesh.setPivotMatrix(oldPivot);
  67587. mesh.computeWorldMatrix(true);
  67588. }
  67589. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  67590. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  67591. //this._tmpPosition.copyFrom(object.position);
  67592. }
  67593. impostor.setDeltaPosition(this._tmpDeltaPosition);
  67594. //Now update the impostor object
  67595. impostor.physicsBody.position.copy(this._tmpPosition);
  67596. impostor.physicsBody.quaternion.copy(quaternion);
  67597. };
  67598. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67599. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67600. if (impostor.object.rotationQuaternion) {
  67601. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67602. }
  67603. };
  67604. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67605. impostor.physicsBody.position.copy(newPosition);
  67606. impostor.physicsBody.quaternion.copy(newRotation);
  67607. };
  67608. CannonJSPlugin.prototype.isSupported = function () {
  67609. return this.BJSCANNON !== undefined;
  67610. };
  67611. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67612. impostor.physicsBody.velocity.copy(velocity);
  67613. };
  67614. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67615. impostor.physicsBody.angularVelocity.copy(velocity);
  67616. };
  67617. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67618. var v = impostor.physicsBody.velocity;
  67619. if (!v) {
  67620. return null;
  67621. }
  67622. return new BABYLON.Vector3(v.x, v.y, v.z);
  67623. };
  67624. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67625. var v = impostor.physicsBody.angularVelocity;
  67626. if (!v) {
  67627. return null;
  67628. }
  67629. return new BABYLON.Vector3(v.x, v.y, v.z);
  67630. };
  67631. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67632. impostor.physicsBody.mass = mass;
  67633. impostor.physicsBody.updateMassProperties();
  67634. };
  67635. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67636. return impostor.physicsBody.mass;
  67637. };
  67638. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67639. return impostor.physicsBody.material.friction;
  67640. };
  67641. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67642. impostor.physicsBody.material.friction = friction;
  67643. };
  67644. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67645. return impostor.physicsBody.material.restitution;
  67646. };
  67647. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67648. impostor.physicsBody.material.restitution = restitution;
  67649. };
  67650. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67651. impostor.physicsBody.sleep();
  67652. };
  67653. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67654. impostor.physicsBody.wakeUp();
  67655. };
  67656. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67657. joint.physicsJoint.distance = maxDistance;
  67658. };
  67659. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67660. // if (!motorIndex) {
  67661. // joint.physicsJoint.enableMotor();
  67662. // }
  67663. // }
  67664. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67665. // if (!motorIndex) {
  67666. // joint.physicsJoint.disableMotor();
  67667. // }
  67668. // }
  67669. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67670. if (!motorIndex) {
  67671. joint.physicsJoint.enableMotor();
  67672. joint.physicsJoint.setMotorSpeed(speed);
  67673. if (maxForce) {
  67674. this.setLimit(joint, maxForce);
  67675. }
  67676. }
  67677. };
  67678. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67679. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67680. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67681. };
  67682. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67683. var body = impostor.physicsBody;
  67684. mesh.position.x = body.position.x;
  67685. mesh.position.y = body.position.y;
  67686. mesh.position.z = body.position.z;
  67687. if (mesh.rotationQuaternion) {
  67688. mesh.rotationQuaternion.x = body.quaternion.x;
  67689. mesh.rotationQuaternion.y = body.quaternion.y;
  67690. mesh.rotationQuaternion.z = body.quaternion.z;
  67691. mesh.rotationQuaternion.w = body.quaternion.w;
  67692. }
  67693. };
  67694. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67695. var shape = impostor.physicsBody.shapes[0];
  67696. return shape.boundingSphereRadius;
  67697. };
  67698. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67699. var shape = impostor.physicsBody.shapes[0];
  67700. result.x = shape.halfExtents.x * 2;
  67701. result.y = shape.halfExtents.y * 2;
  67702. result.z = shape.halfExtents.z * 2;
  67703. };
  67704. CannonJSPlugin.prototype.dispose = function () {
  67705. };
  67706. return CannonJSPlugin;
  67707. }());
  67708. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67709. })(BABYLON || (BABYLON = {}));
  67710. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67711. var BABYLON;
  67712. (function (BABYLON) {
  67713. var OimoJSPlugin = /** @class */ (function () {
  67714. function OimoJSPlugin(iterations) {
  67715. this.name = "OimoJSPlugin";
  67716. this._tmpImpostorsArray = [];
  67717. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67718. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  67719. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67720. this.world.worldscale(1);
  67721. this.world.clear();
  67722. //making sure no stats are calculated
  67723. this.world.isNoStat = true;
  67724. }
  67725. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67726. this.world.gravity.copy(gravity);
  67727. };
  67728. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67729. this.world.timeStep = timeStep;
  67730. };
  67731. OimoJSPlugin.prototype.getTimeStep = function () {
  67732. return this.world.timeStep;
  67733. };
  67734. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67735. var _this = this;
  67736. impostors.forEach(function (impostor) {
  67737. impostor.beforeStep();
  67738. });
  67739. this.world.step();
  67740. impostors.forEach(function (impostor) {
  67741. impostor.afterStep();
  67742. //update the ordered impostors array
  67743. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67744. });
  67745. //check for collisions
  67746. var contact = this.world.contacts;
  67747. while (contact !== null) {
  67748. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67749. contact = contact.next;
  67750. continue;
  67751. }
  67752. //is this body colliding with any other? get the impostor
  67753. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67754. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67755. if (!mainImpostor || !collidingImpostor) {
  67756. contact = contact.next;
  67757. continue;
  67758. }
  67759. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67760. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67761. contact = contact.next;
  67762. }
  67763. };
  67764. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67765. var mass = impostor.physicsBody.massInfo.mass;
  67766. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67767. };
  67768. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67769. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67770. this.applyImpulse(impostor, force, contactPoint);
  67771. };
  67772. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67773. var _this = this;
  67774. //parent-child relationship. Does this impostor has a parent impostor?
  67775. if (impostor.parent) {
  67776. if (impostor.physicsBody) {
  67777. this.removePhysicsBody(impostor);
  67778. //TODO is that needed?
  67779. impostor.forceUpdate();
  67780. }
  67781. return;
  67782. }
  67783. if (impostor.isBodyInitRequired()) {
  67784. var bodyConfig = {
  67785. name: impostor.uniqueId,
  67786. //Oimo must have mass, also for static objects.
  67787. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67788. size: [],
  67789. type: [],
  67790. pos: [],
  67791. rot: [],
  67792. move: impostor.getParam("mass") !== 0,
  67793. //Supporting older versions of Oimo
  67794. world: this.world
  67795. };
  67796. var impostors = [impostor];
  67797. var addToArray = function (parent) {
  67798. if (!parent.getChildMeshes)
  67799. return;
  67800. parent.getChildMeshes().forEach(function (m) {
  67801. if (m.physicsImpostor) {
  67802. impostors.push(m.physicsImpostor);
  67803. //m.physicsImpostor._init();
  67804. }
  67805. });
  67806. };
  67807. addToArray(impostor.object);
  67808. var checkWithEpsilon_1 = function (value) {
  67809. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67810. };
  67811. impostors.forEach(function (i) {
  67812. if (!impostor.object.rotationQuaternion) {
  67813. return;
  67814. }
  67815. //get the correct bounding box
  67816. var oldQuaternion = i.object.rotationQuaternion;
  67817. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67818. x: impostor.object.rotationQuaternion.x,
  67819. y: impostor.object.rotationQuaternion.y,
  67820. z: impostor.object.rotationQuaternion.z,
  67821. s: impostor.object.rotationQuaternion.w
  67822. });
  67823. var extendSize = i.getObjectExtendSize();
  67824. if (i === impostor) {
  67825. var center = impostor.getObjectCenter();
  67826. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67827. //Can also use Array.prototype.push.apply
  67828. bodyConfig.pos.push(center.x);
  67829. bodyConfig.pos.push(center.y);
  67830. bodyConfig.pos.push(center.z);
  67831. //tmp solution
  67832. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67833. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67834. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67835. }
  67836. else {
  67837. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67838. bodyConfig.pos.push(localPosition.x);
  67839. bodyConfig.pos.push(localPosition.y);
  67840. bodyConfig.pos.push(localPosition.z);
  67841. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67842. bodyConfig.rot.push(0);
  67843. bodyConfig.rot.push(0);
  67844. bodyConfig.rot.push(0);
  67845. }
  67846. // register mesh
  67847. switch (i.type) {
  67848. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67849. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67850. case BABYLON.PhysicsImpostor.SphereImpostor:
  67851. var radiusX = extendSize.x;
  67852. var radiusY = extendSize.y;
  67853. var radiusZ = extendSize.z;
  67854. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67855. bodyConfig.type.push('sphere');
  67856. //due to the way oimo works with compounds, add 3 times
  67857. bodyConfig.size.push(size);
  67858. bodyConfig.size.push(size);
  67859. bodyConfig.size.push(size);
  67860. break;
  67861. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67862. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67863. var sizeY = checkWithEpsilon_1(extendSize.y);
  67864. bodyConfig.type.push('cylinder');
  67865. bodyConfig.size.push(sizeX);
  67866. bodyConfig.size.push(sizeY);
  67867. //due to the way oimo works with compounds, add one more value.
  67868. bodyConfig.size.push(sizeY);
  67869. break;
  67870. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67871. case BABYLON.PhysicsImpostor.BoxImpostor:
  67872. default:
  67873. var sizeX = checkWithEpsilon_1(extendSize.x);
  67874. var sizeY = checkWithEpsilon_1(extendSize.y);
  67875. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67876. bodyConfig.type.push('box');
  67877. bodyConfig.size.push(sizeX);
  67878. bodyConfig.size.push(sizeY);
  67879. bodyConfig.size.push(sizeZ);
  67880. break;
  67881. }
  67882. //actually not needed, but hey...
  67883. i.object.rotationQuaternion = oldQuaternion;
  67884. });
  67885. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67886. }
  67887. else {
  67888. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67889. }
  67890. impostor.setDeltaPosition(this._tmpPositionVector);
  67891. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67892. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67893. };
  67894. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67895. //impostor.physicsBody.dispose();
  67896. //Same as : (older oimo versions)
  67897. this.world.removeRigidBody(impostor.physicsBody);
  67898. };
  67899. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67900. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67901. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67902. if (!mainBody || !connectedBody) {
  67903. return;
  67904. }
  67905. var jointData = impostorJoint.joint.jointData;
  67906. var options = jointData.nativeParams || {};
  67907. var type;
  67908. var nativeJointData = {
  67909. body1: mainBody,
  67910. body2: connectedBody,
  67911. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  67912. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  67913. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  67914. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  67915. min: options.min,
  67916. max: options.max,
  67917. collision: options.collision || jointData.collision,
  67918. spring: options.spring,
  67919. //supporting older version of Oimo
  67920. world: this.world
  67921. };
  67922. switch (impostorJoint.joint.type) {
  67923. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67924. type = "jointBall";
  67925. break;
  67926. case BABYLON.PhysicsJoint.SpringJoint:
  67927. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  67928. var springData = jointData;
  67929. nativeJointData.min = springData.length || nativeJointData.min;
  67930. //Max should also be set, just make sure it is at least min
  67931. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  67932. case BABYLON.PhysicsJoint.DistanceJoint:
  67933. type = "jointDistance";
  67934. nativeJointData.max = jointData.maxDistance;
  67935. break;
  67936. case BABYLON.PhysicsJoint.PrismaticJoint:
  67937. type = "jointPrisme";
  67938. break;
  67939. case BABYLON.PhysicsJoint.SliderJoint:
  67940. type = "jointSlide";
  67941. break;
  67942. case BABYLON.PhysicsJoint.WheelJoint:
  67943. type = "jointWheel";
  67944. break;
  67945. case BABYLON.PhysicsJoint.HingeJoint:
  67946. default:
  67947. type = "jointHinge";
  67948. break;
  67949. }
  67950. nativeJointData.type = type;
  67951. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  67952. };
  67953. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67954. //Bug in Oimo prevents us from disposing a joint in the playground
  67955. //joint.joint.physicsJoint.dispose();
  67956. //So we will bruteforce it!
  67957. try {
  67958. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  67959. }
  67960. catch (e) {
  67961. BABYLON.Tools.Warn(e);
  67962. }
  67963. };
  67964. OimoJSPlugin.prototype.isSupported = function () {
  67965. return this.BJSOIMO !== undefined;
  67966. };
  67967. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67968. if (!impostor.physicsBody.sleeping) {
  67969. //TODO check that
  67970. if (impostor.physicsBody.shapes.next) {
  67971. var parentShape = this._getLastShape(impostor.physicsBody);
  67972. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  67973. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  67974. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  67975. }
  67976. else {
  67977. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  67978. }
  67979. if (impostor.object.rotationQuaternion) {
  67980. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  67981. impostor.object.rotationQuaternion.normalize();
  67982. }
  67983. }
  67984. };
  67985. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67986. var body = impostor.physicsBody;
  67987. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  67988. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  67989. body.syncShapes();
  67990. body.awake();
  67991. };
  67992. OimoJSPlugin.prototype._getLastShape = function (body) {
  67993. var lastShape = body.shapes;
  67994. while (lastShape.next) {
  67995. lastShape = lastShape.next;
  67996. }
  67997. return lastShape;
  67998. };
  67999. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68000. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68001. };
  68002. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68003. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68004. };
  68005. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68006. var v = impostor.physicsBody.linearVelocity;
  68007. if (!v) {
  68008. return null;
  68009. }
  68010. return new BABYLON.Vector3(v.x, v.y, v.z);
  68011. };
  68012. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68013. var v = impostor.physicsBody.angularVelocity;
  68014. if (!v) {
  68015. return null;
  68016. }
  68017. return new BABYLON.Vector3(v.x, v.y, v.z);
  68018. };
  68019. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68020. var staticBody = mass === 0;
  68021. //this will actually set the body's density and not its mass.
  68022. //But this is how oimo treats the mass variable.
  68023. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68024. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68025. };
  68026. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68027. return impostor.physicsBody.shapes.density;
  68028. };
  68029. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68030. return impostor.physicsBody.shapes.friction;
  68031. };
  68032. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68033. impostor.physicsBody.shapes.friction = friction;
  68034. };
  68035. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68036. return impostor.physicsBody.shapes.restitution;
  68037. };
  68038. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68039. impostor.physicsBody.shapes.restitution = restitution;
  68040. };
  68041. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68042. impostor.physicsBody.sleep();
  68043. };
  68044. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68045. impostor.physicsBody.awake();
  68046. };
  68047. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68048. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68049. if (minDistance !== void 0) {
  68050. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68051. }
  68052. };
  68053. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68054. //TODO separate rotational and transational motors.
  68055. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68056. if (motor) {
  68057. motor.setMotor(speed, maxForce);
  68058. }
  68059. };
  68060. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68061. //TODO separate rotational and transational motors.
  68062. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68063. if (motor) {
  68064. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68065. }
  68066. };
  68067. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68068. var body = impostor.physicsBody;
  68069. mesh.position.x = body.position.x;
  68070. mesh.position.y = body.position.y;
  68071. mesh.position.z = body.position.z;
  68072. if (mesh.rotationQuaternion) {
  68073. mesh.rotationQuaternion.x = body.orientation.x;
  68074. mesh.rotationQuaternion.y = body.orientation.y;
  68075. mesh.rotationQuaternion.z = body.orientation.z;
  68076. mesh.rotationQuaternion.w = body.orientation.s;
  68077. }
  68078. };
  68079. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68080. return impostor.physicsBody.shapes.radius;
  68081. };
  68082. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68083. var shape = impostor.physicsBody.shapes;
  68084. result.x = shape.halfWidth * 2;
  68085. result.y = shape.halfHeight * 2;
  68086. result.z = shape.halfDepth * 2;
  68087. };
  68088. OimoJSPlugin.prototype.dispose = function () {
  68089. this.world.clear();
  68090. };
  68091. return OimoJSPlugin;
  68092. }());
  68093. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68094. })(BABYLON || (BABYLON = {}));
  68095. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68096. var BABYLON;
  68097. (function (BABYLON) {
  68098. var Internals;
  68099. (function (Internals) {
  68100. /*
  68101. * Based on jsTGALoader - Javascript loader for TGA file
  68102. * By Vincent Thibault
  68103. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68104. */
  68105. var TGATools = /** @class */ (function () {
  68106. function TGATools() {
  68107. }
  68108. TGATools.GetTGAHeader = function (data) {
  68109. var offset = 0;
  68110. var header = {
  68111. id_length: data[offset++],
  68112. colormap_type: data[offset++],
  68113. image_type: data[offset++],
  68114. colormap_index: data[offset++] | data[offset++] << 8,
  68115. colormap_length: data[offset++] | data[offset++] << 8,
  68116. colormap_size: data[offset++],
  68117. origin: [
  68118. data[offset++] | data[offset++] << 8,
  68119. data[offset++] | data[offset++] << 8
  68120. ],
  68121. width: data[offset++] | data[offset++] << 8,
  68122. height: data[offset++] | data[offset++] << 8,
  68123. pixel_size: data[offset++],
  68124. flags: data[offset++]
  68125. };
  68126. return header;
  68127. };
  68128. TGATools.UploadContent = function (gl, data) {
  68129. // Not enough data to contain header ?
  68130. if (data.length < 19) {
  68131. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68132. return;
  68133. }
  68134. // Read Header
  68135. var offset = 18;
  68136. var header = TGATools.GetTGAHeader(data);
  68137. // Assume it's a valid Targa file.
  68138. if (header.id_length + offset > data.length) {
  68139. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  68140. return;
  68141. }
  68142. // Skip not needed data
  68143. offset += header.id_length;
  68144. var use_rle = false;
  68145. var use_pal = false;
  68146. var use_grey = false;
  68147. // Get some informations.
  68148. switch (header.image_type) {
  68149. case TGATools._TYPE_RLE_INDEXED:
  68150. use_rle = true;
  68151. case TGATools._TYPE_INDEXED:
  68152. use_pal = true;
  68153. break;
  68154. case TGATools._TYPE_RLE_RGB:
  68155. use_rle = true;
  68156. case TGATools._TYPE_RGB:
  68157. // use_rgb = true;
  68158. break;
  68159. case TGATools._TYPE_RLE_GREY:
  68160. use_rle = true;
  68161. case TGATools._TYPE_GREY:
  68162. use_grey = true;
  68163. break;
  68164. }
  68165. var pixel_data;
  68166. // var numAlphaBits = header.flags & 0xf;
  68167. var pixel_size = header.pixel_size >> 3;
  68168. var pixel_total = header.width * header.height * pixel_size;
  68169. // Read palettes
  68170. var palettes;
  68171. if (use_pal) {
  68172. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  68173. }
  68174. // Read LRE
  68175. if (use_rle) {
  68176. pixel_data = new Uint8Array(pixel_total);
  68177. var c, count, i;
  68178. var localOffset = 0;
  68179. var pixels = new Uint8Array(pixel_size);
  68180. while (offset < pixel_total && localOffset < pixel_total) {
  68181. c = data[offset++];
  68182. count = (c & 0x7f) + 1;
  68183. // RLE pixels
  68184. if (c & 0x80) {
  68185. // Bind pixel tmp array
  68186. for (i = 0; i < pixel_size; ++i) {
  68187. pixels[i] = data[offset++];
  68188. }
  68189. // Copy pixel array
  68190. for (i = 0; i < count; ++i) {
  68191. pixel_data.set(pixels, localOffset + i * pixel_size);
  68192. }
  68193. localOffset += pixel_size * count;
  68194. }
  68195. else {
  68196. count *= pixel_size;
  68197. for (i = 0; i < count; ++i) {
  68198. pixel_data[localOffset + i] = data[offset++];
  68199. }
  68200. localOffset += count;
  68201. }
  68202. }
  68203. }
  68204. else {
  68205. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  68206. }
  68207. // Load to texture
  68208. var x_start, y_start, x_step, y_step, y_end, x_end;
  68209. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  68210. default:
  68211. case TGATools._ORIGIN_UL:
  68212. x_start = 0;
  68213. x_step = 1;
  68214. x_end = header.width;
  68215. y_start = 0;
  68216. y_step = 1;
  68217. y_end = header.height;
  68218. break;
  68219. case TGATools._ORIGIN_BL:
  68220. x_start = 0;
  68221. x_step = 1;
  68222. x_end = header.width;
  68223. y_start = header.height - 1;
  68224. y_step = -1;
  68225. y_end = -1;
  68226. break;
  68227. case TGATools._ORIGIN_UR:
  68228. x_start = header.width - 1;
  68229. x_step = -1;
  68230. x_end = -1;
  68231. y_start = 0;
  68232. y_step = 1;
  68233. y_end = header.height;
  68234. break;
  68235. case TGATools._ORIGIN_BR:
  68236. x_start = header.width - 1;
  68237. x_step = -1;
  68238. x_end = -1;
  68239. y_start = header.height - 1;
  68240. y_step = -1;
  68241. y_end = -1;
  68242. break;
  68243. }
  68244. // Load the specify method
  68245. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  68246. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  68247. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68248. };
  68249. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68250. var image = pixel_data, colormap = palettes;
  68251. var width = header.width, height = header.height;
  68252. var color, i = 0, x, y;
  68253. var imageData = new Uint8Array(width * height * 4);
  68254. for (y = y_start; y !== y_end; y += y_step) {
  68255. for (x = x_start; x !== x_end; x += x_step, i++) {
  68256. color = image[i];
  68257. imageData[(x + width * y) * 4 + 3] = 255;
  68258. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  68259. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  68260. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  68261. }
  68262. }
  68263. return imageData;
  68264. };
  68265. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68266. var image = pixel_data;
  68267. var width = header.width, height = header.height;
  68268. var color, i = 0, x, y;
  68269. var imageData = new Uint8Array(width * height * 4);
  68270. for (y = y_start; y !== y_end; y += y_step) {
  68271. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68272. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  68273. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  68274. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  68275. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  68276. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  68277. }
  68278. }
  68279. return imageData;
  68280. };
  68281. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68282. var image = pixel_data;
  68283. var width = header.width, height = header.height;
  68284. var i = 0, x, y;
  68285. var imageData = new Uint8Array(width * height * 4);
  68286. for (y = y_start; y !== y_end; y += y_step) {
  68287. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  68288. imageData[(x + width * y) * 4 + 3] = 255;
  68289. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68290. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68291. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68292. }
  68293. }
  68294. return imageData;
  68295. };
  68296. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68297. var image = pixel_data;
  68298. var width = header.width, height = header.height;
  68299. var i = 0, x, y;
  68300. var imageData = new Uint8Array(width * height * 4);
  68301. for (y = y_start; y !== y_end; y += y_step) {
  68302. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  68303. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68304. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68305. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68306. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68307. }
  68308. }
  68309. return imageData;
  68310. };
  68311. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68312. var image = pixel_data;
  68313. var width = header.width, height = header.height;
  68314. var color, i = 0, x, y;
  68315. var imageData = new Uint8Array(width * height * 4);
  68316. for (y = y_start; y !== y_end; y += y_step) {
  68317. for (x = x_start; x !== x_end; x += x_step, i++) {
  68318. color = image[i];
  68319. imageData[(x + width * y) * 4 + 0] = color;
  68320. imageData[(x + width * y) * 4 + 1] = color;
  68321. imageData[(x + width * y) * 4 + 2] = color;
  68322. imageData[(x + width * y) * 4 + 3] = 255;
  68323. }
  68324. }
  68325. return imageData;
  68326. };
  68327. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68328. var image = pixel_data;
  68329. var width = header.width, height = header.height;
  68330. var i = 0, x, y;
  68331. var imageData = new Uint8Array(width * height * 4);
  68332. for (y = y_start; y !== y_end; y += y_step) {
  68333. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68334. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68335. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68336. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68337. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68338. }
  68339. }
  68340. return imageData;
  68341. };
  68342. //private static _TYPE_NO_DATA = 0;
  68343. TGATools._TYPE_INDEXED = 1;
  68344. TGATools._TYPE_RGB = 2;
  68345. TGATools._TYPE_GREY = 3;
  68346. TGATools._TYPE_RLE_INDEXED = 9;
  68347. TGATools._TYPE_RLE_RGB = 10;
  68348. TGATools._TYPE_RLE_GREY = 11;
  68349. TGATools._ORIGIN_MASK = 0x30;
  68350. TGATools._ORIGIN_SHIFT = 0x04;
  68351. TGATools._ORIGIN_BL = 0x00;
  68352. TGATools._ORIGIN_BR = 0x01;
  68353. TGATools._ORIGIN_UL = 0x02;
  68354. TGATools._ORIGIN_UR = 0x03;
  68355. return TGATools;
  68356. }());
  68357. Internals.TGATools = TGATools;
  68358. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68359. })(BABYLON || (BABYLON = {}));
  68360. //# sourceMappingURL=babylon.tga.js.map
  68361. var BABYLON;
  68362. (function (BABYLON) {
  68363. var Internals;
  68364. (function (Internals) {
  68365. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68366. // All values and structures referenced from:
  68367. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68368. var DDS_MAGIC = 0x20534444;
  68369. var
  68370. //DDSD_CAPS = 0x1,
  68371. //DDSD_HEIGHT = 0x2,
  68372. //DDSD_WIDTH = 0x4,
  68373. //DDSD_PITCH = 0x8,
  68374. //DDSD_PIXELFORMAT = 0x1000,
  68375. DDSD_MIPMAPCOUNT = 0x20000;
  68376. //DDSD_LINEARSIZE = 0x80000,
  68377. //DDSD_DEPTH = 0x800000;
  68378. // var DDSCAPS_COMPLEX = 0x8,
  68379. // DDSCAPS_MIPMAP = 0x400000,
  68380. // DDSCAPS_TEXTURE = 0x1000;
  68381. var DDSCAPS2_CUBEMAP = 0x200;
  68382. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68383. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68384. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68385. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68386. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68387. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68388. // DDSCAPS2_VOLUME = 0x200000;
  68389. var
  68390. //DDPF_ALPHAPIXELS = 0x1,
  68391. //DDPF_ALPHA = 0x2,
  68392. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68393. //DDPF_YUV = 0x200,
  68394. DDPF_LUMINANCE = 0x20000;
  68395. function FourCCToInt32(value) {
  68396. return value.charCodeAt(0) +
  68397. (value.charCodeAt(1) << 8) +
  68398. (value.charCodeAt(2) << 16) +
  68399. (value.charCodeAt(3) << 24);
  68400. }
  68401. function Int32ToFourCC(value) {
  68402. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68403. }
  68404. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68405. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68406. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68407. var FOURCC_DX10 = FourCCToInt32("DX10");
  68408. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68409. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68410. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68411. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68412. var headerLengthInt = 31; // The header length in 32 bit ints
  68413. // Offsets into the header array
  68414. var off_magic = 0;
  68415. var off_size = 1;
  68416. var off_flags = 2;
  68417. var off_height = 3;
  68418. var off_width = 4;
  68419. var off_mipmapCount = 7;
  68420. var off_pfFlags = 20;
  68421. var off_pfFourCC = 21;
  68422. var off_RGBbpp = 22;
  68423. // var off_RMask = 23;
  68424. // var off_GMask = 24;
  68425. // var off_BMask = 25;
  68426. // var off_AMask = 26;
  68427. // var off_caps1 = 27;
  68428. var off_caps2 = 28;
  68429. // var off_caps3 = 29;
  68430. // var off_caps4 = 30;
  68431. var off_dxgiFormat = 32;
  68432. ;
  68433. var DDSTools = /** @class */ (function () {
  68434. function DDSTools() {
  68435. }
  68436. DDSTools.GetDDSInfo = function (arrayBuffer) {
  68437. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68438. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  68439. var mipmapCount = 1;
  68440. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  68441. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68442. }
  68443. var fourCC = header[off_pfFourCC];
  68444. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  68445. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68446. switch (fourCC) {
  68447. case FOURCC_D3DFMT_R16G16B16A16F:
  68448. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68449. break;
  68450. case FOURCC_D3DFMT_R32G32B32A32F:
  68451. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68452. break;
  68453. case FOURCC_DX10:
  68454. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  68455. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68456. break;
  68457. }
  68458. }
  68459. return {
  68460. width: header[off_width],
  68461. height: header[off_height],
  68462. mipmapCount: mipmapCount,
  68463. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  68464. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  68465. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  68466. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  68467. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  68468. dxgiFormat: dxgiFormat,
  68469. textureType: textureType
  68470. };
  68471. };
  68472. DDSTools._ToHalfFloat = function (value) {
  68473. if (!DDSTools._FloatView) {
  68474. DDSTools._FloatView = new Float32Array(1);
  68475. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  68476. }
  68477. DDSTools._FloatView[0] = value;
  68478. var x = DDSTools._Int32View[0];
  68479. var bits = (x >> 16) & 0x8000; /* Get the sign */
  68480. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  68481. var e = (x >> 23) & 0xff; /* Using int is faster here */
  68482. /* If zero, or denormal, or exponent underflows too much for a denormal
  68483. * half, return signed zero. */
  68484. if (e < 103) {
  68485. return bits;
  68486. }
  68487. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  68488. if (e > 142) {
  68489. bits |= 0x7c00;
  68490. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  68491. * not Inf, so make sure we set one mantissa bit too. */
  68492. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  68493. return bits;
  68494. }
  68495. /* If exponent underflows but not too much, return a denormal */
  68496. if (e < 113) {
  68497. m |= 0x0800;
  68498. /* Extra rounding may overflow and set mantissa to 0 and exponent
  68499. * to 1, which is OK. */
  68500. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  68501. return bits;
  68502. }
  68503. bits |= ((e - 112) << 10) | (m >> 1);
  68504. bits += m & 1;
  68505. return bits;
  68506. };
  68507. DDSTools._FromHalfFloat = function (value) {
  68508. var s = (value & 0x8000) >> 15;
  68509. var e = (value & 0x7C00) >> 10;
  68510. var f = value & 0x03FF;
  68511. if (e === 0) {
  68512. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  68513. }
  68514. else if (e == 0x1F) {
  68515. return f ? NaN : ((s ? -1 : 1) * Infinity);
  68516. }
  68517. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  68518. };
  68519. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68520. var destArray = new Float32Array(dataLength);
  68521. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68522. var index = 0;
  68523. for (var y = 0; y < height; y++) {
  68524. for (var x = 0; x < width; x++) {
  68525. var srcPos = (x + y * width) * 4;
  68526. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  68527. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  68528. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  68529. if (DDSTools.StoreLODInAlphaChannel) {
  68530. destArray[index + 3] = lod;
  68531. }
  68532. else {
  68533. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  68534. }
  68535. index += 4;
  68536. }
  68537. }
  68538. return destArray;
  68539. };
  68540. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68541. if (DDSTools.StoreLODInAlphaChannel) {
  68542. var destArray = new Uint16Array(dataLength);
  68543. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68544. var index = 0;
  68545. for (var y = 0; y < height; y++) {
  68546. for (var x = 0; x < width; x++) {
  68547. var srcPos = (x + y * width) * 4;
  68548. destArray[index] = srcData[srcPos];
  68549. destArray[index + 1] = srcData[srcPos + 1];
  68550. destArray[index + 2] = srcData[srcPos + 2];
  68551. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  68552. index += 4;
  68553. }
  68554. }
  68555. return destArray;
  68556. }
  68557. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  68558. };
  68559. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68560. if (DDSTools.StoreLODInAlphaChannel) {
  68561. var destArray = new Float32Array(dataLength);
  68562. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68563. var index = 0;
  68564. for (var y = 0; y < height; y++) {
  68565. for (var x = 0; x < width; x++) {
  68566. var srcPos = (x + y * width) * 4;
  68567. destArray[index] = srcData[srcPos];
  68568. destArray[index + 1] = srcData[srcPos + 1];
  68569. destArray[index + 2] = srcData[srcPos + 2];
  68570. destArray[index + 3] = lod;
  68571. index += 4;
  68572. }
  68573. }
  68574. return destArray;
  68575. }
  68576. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  68577. };
  68578. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68579. var destArray = new Uint8Array(dataLength);
  68580. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68581. var index = 0;
  68582. for (var y = 0; y < height; y++) {
  68583. for (var x = 0; x < width; x++) {
  68584. var srcPos = (x + y * width) * 4;
  68585. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  68586. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  68587. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  68588. if (DDSTools.StoreLODInAlphaChannel) {
  68589. destArray[index + 3] = lod;
  68590. }
  68591. else {
  68592. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  68593. }
  68594. index += 4;
  68595. }
  68596. }
  68597. return destArray;
  68598. };
  68599. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68600. var destArray = new Uint8Array(dataLength);
  68601. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68602. var index = 0;
  68603. for (var y = 0; y < height; y++) {
  68604. for (var x = 0; x < width; x++) {
  68605. var srcPos = (x + y * width) * 4;
  68606. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  68607. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  68608. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  68609. if (DDSTools.StoreLODInAlphaChannel) {
  68610. destArray[index + 3] = lod;
  68611. }
  68612. else {
  68613. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  68614. }
  68615. index += 4;
  68616. }
  68617. }
  68618. return destArray;
  68619. };
  68620. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68621. var byteArray = new Uint8Array(dataLength);
  68622. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68623. var index = 0;
  68624. for (var y = 0; y < height; y++) {
  68625. for (var x = 0; x < width; x++) {
  68626. var srcPos = (x + y * width) * 4;
  68627. byteArray[index] = srcData[srcPos + 2];
  68628. byteArray[index + 1] = srcData[srcPos + 1];
  68629. byteArray[index + 2] = srcData[srcPos];
  68630. byteArray[index + 3] = srcData[srcPos + 3];
  68631. index += 4;
  68632. }
  68633. }
  68634. return byteArray;
  68635. };
  68636. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68637. var byteArray = new Uint8Array(dataLength);
  68638. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68639. var index = 0;
  68640. for (var y = 0; y < height; y++) {
  68641. for (var x = 0; x < width; x++) {
  68642. var srcPos = (x + y * width) * 3;
  68643. byteArray[index] = srcData[srcPos + 2];
  68644. byteArray[index + 1] = srcData[srcPos + 1];
  68645. byteArray[index + 2] = srcData[srcPos];
  68646. index += 3;
  68647. }
  68648. }
  68649. return byteArray;
  68650. };
  68651. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68652. var byteArray = new Uint8Array(dataLength);
  68653. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68654. var index = 0;
  68655. for (var y = 0; y < height; y++) {
  68656. for (var x = 0; x < width; x++) {
  68657. var srcPos = (x + y * width);
  68658. byteArray[index] = srcData[srcPos];
  68659. index++;
  68660. }
  68661. }
  68662. return byteArray;
  68663. };
  68664. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  68665. if (lodIndex === void 0) { lodIndex = -1; }
  68666. var ext = engine.getCaps().s3tc;
  68667. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68668. var fourCC, width, height, dataLength = 0, dataOffset;
  68669. var byteArray, mipmapCount, mip;
  68670. var internalFormat = 0;
  68671. var format = 0;
  68672. var blockBytes = 1;
  68673. if (header[off_magic] !== DDS_MAGIC) {
  68674. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68675. return;
  68676. }
  68677. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68678. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68679. return;
  68680. }
  68681. if (info.isCompressed && !ext) {
  68682. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68683. return;
  68684. }
  68685. var bpp = header[off_RGBbpp];
  68686. dataOffset = header[off_size] + 4;
  68687. var computeFormats = false;
  68688. if (info.isFourCC) {
  68689. fourCC = header[off_pfFourCC];
  68690. switch (fourCC) {
  68691. case FOURCC_DXT1:
  68692. blockBytes = 8;
  68693. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68694. break;
  68695. case FOURCC_DXT3:
  68696. blockBytes = 16;
  68697. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68698. break;
  68699. case FOURCC_DXT5:
  68700. blockBytes = 16;
  68701. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68702. break;
  68703. case FOURCC_D3DFMT_R16G16B16A16F:
  68704. computeFormats = true;
  68705. break;
  68706. case FOURCC_D3DFMT_R32G32B32A32F:
  68707. computeFormats = true;
  68708. break;
  68709. case FOURCC_DX10:
  68710. // There is an additionnal header so dataOffset need to be changed
  68711. dataOffset += 5 * 4; // 5 uints
  68712. var supported = false;
  68713. switch (info.dxgiFormat) {
  68714. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68715. computeFormats = true;
  68716. supported = true;
  68717. break;
  68718. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68719. info.isRGB = true;
  68720. info.isFourCC = false;
  68721. bpp = 32;
  68722. supported = true;
  68723. break;
  68724. }
  68725. if (supported) {
  68726. break;
  68727. }
  68728. default:
  68729. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68730. return;
  68731. }
  68732. }
  68733. if (computeFormats) {
  68734. format = engine._getWebGLTextureType(info.textureType);
  68735. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68736. }
  68737. mipmapCount = 1;
  68738. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68739. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68740. }
  68741. for (var face = 0; face < faces; face++) {
  68742. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  68743. width = header[off_width];
  68744. height = header[off_height];
  68745. for (mip = 0; mip < mipmapCount; ++mip) {
  68746. if (lodIndex === -1 || lodIndex === mip) {
  68747. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68748. var i = (lodIndex === -1) ? mip : 0;
  68749. if (!info.isCompressed && info.isFourCC) {
  68750. dataLength = width * height * 4;
  68751. var floatArray = null;
  68752. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68753. if (bpp === 128) {
  68754. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68755. }
  68756. else if (bpp === 64) {
  68757. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68758. }
  68759. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68760. format = engine._getWebGLTextureType(info.textureType);
  68761. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68762. }
  68763. else {
  68764. if (bpp === 128) {
  68765. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68766. }
  68767. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68768. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68769. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68770. format = engine._getWebGLTextureType(info.textureType);
  68771. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68772. }
  68773. else {
  68774. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68775. }
  68776. }
  68777. if (floatArray) {
  68778. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  68779. }
  68780. }
  68781. else if (info.isRGB) {
  68782. if (bpp === 24) {
  68783. dataLength = width * height * 3;
  68784. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68785. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68786. }
  68787. else {
  68788. dataLength = width * height * 4;
  68789. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68790. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68791. }
  68792. }
  68793. else if (info.isLuminance) {
  68794. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68795. var unpaddedRowSize = width;
  68796. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68797. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68798. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68799. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68800. }
  68801. else {
  68802. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68803. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68804. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68805. }
  68806. }
  68807. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  68808. width *= 0.5;
  68809. height *= 0.5;
  68810. width = Math.max(1.0, width);
  68811. height = Math.max(1.0, height);
  68812. }
  68813. if (currentFace !== undefined) {
  68814. // Loading a single face
  68815. break;
  68816. }
  68817. }
  68818. };
  68819. DDSTools.StoreLODInAlphaChannel = false;
  68820. return DDSTools;
  68821. }());
  68822. Internals.DDSTools = DDSTools;
  68823. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68824. })(BABYLON || (BABYLON = {}));
  68825. //# sourceMappingURL=babylon.dds.js.map
  68826. var BABYLON;
  68827. (function (BABYLON) {
  68828. var Internals;
  68829. (function (Internals) {
  68830. /**
  68831. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68832. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68833. */
  68834. var KhronosTextureContainer = /** @class */ (function () {
  68835. /**
  68836. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68837. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68838. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68839. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68840. */
  68841. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68842. this.arrayBuffer = arrayBuffer;
  68843. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68844. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68845. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68846. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68847. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68848. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68849. BABYLON.Tools.Error("texture missing KTX identifier");
  68850. return;
  68851. }
  68852. // load the reset of the header in native 32 bit int
  68853. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68854. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68855. var oppositeEndianess = header[0] === 0x01020304;
  68856. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68857. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68858. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68859. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68860. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68861. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68862. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68863. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68864. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68865. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68866. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68867. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68868. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68869. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68870. if (this.glType !== 0) {
  68871. BABYLON.Tools.Error("only compressed formats currently supported");
  68872. return;
  68873. }
  68874. else {
  68875. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68876. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68877. }
  68878. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68879. BABYLON.Tools.Error("only 2D textures currently supported");
  68880. return;
  68881. }
  68882. if (this.numberOfArrayElements !== 0) {
  68883. BABYLON.Tools.Error("texture arrays not currently supported");
  68884. return;
  68885. }
  68886. if (this.numberOfFaces !== facesExpected) {
  68887. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68888. return;
  68889. }
  68890. // we now have a completely validated file, so could use existence of loadType as success
  68891. // would need to make this more elaborate & adjust checks above to support more than one load type
  68892. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68893. }
  68894. // not as fast hardware based, but will probably never need to use
  68895. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68896. return ((val & 0xFF) << 24)
  68897. | ((val & 0xFF00) << 8)
  68898. | ((val >> 8) & 0xFF00)
  68899. | ((val >> 24) & 0xFF);
  68900. };
  68901. /**
  68902. * It is assumed that the texture has already been created & is currently bound
  68903. */
  68904. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  68905. switch (this.loadType) {
  68906. case KhronosTextureContainer.COMPRESSED_2D:
  68907. this._upload2DCompressedLevels(gl, loadMipmaps);
  68908. break;
  68909. case KhronosTextureContainer.TEX_2D:
  68910. case KhronosTextureContainer.COMPRESSED_3D:
  68911. case KhronosTextureContainer.TEX_3D:
  68912. }
  68913. };
  68914. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  68915. // initialize width & height for level 1
  68916. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  68917. var width = this.pixelWidth;
  68918. var height = this.pixelHeight;
  68919. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  68920. for (var level = 0; level < mipmapCount; level++) {
  68921. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  68922. for (var face = 0; face < this.numberOfFaces; face++) {
  68923. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68924. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  68925. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  68926. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  68927. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  68928. }
  68929. width = Math.max(1.0, width * 0.5);
  68930. height = Math.max(1.0, height * 0.5);
  68931. }
  68932. };
  68933. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  68934. // load types
  68935. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  68936. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  68937. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  68938. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  68939. return KhronosTextureContainer;
  68940. }());
  68941. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68942. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68943. })(BABYLON || (BABYLON = {}));
  68944. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  68945. var BABYLON;
  68946. (function (BABYLON) {
  68947. var Debug;
  68948. (function (Debug) {
  68949. /**
  68950. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  68951. */
  68952. var SkeletonViewer = /** @class */ (function () {
  68953. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  68954. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  68955. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  68956. this.skeleton = skeleton;
  68957. this.mesh = mesh;
  68958. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  68959. this.renderingGroupId = renderingGroupId;
  68960. this.color = BABYLON.Color3.White();
  68961. this._debugLines = new Array();
  68962. this._isEnabled = false;
  68963. this._scene = scene;
  68964. this.update();
  68965. this._renderFunction = this.update.bind(this);
  68966. }
  68967. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  68968. get: function () {
  68969. return this._isEnabled;
  68970. },
  68971. set: function (value) {
  68972. if (this._isEnabled === value) {
  68973. return;
  68974. }
  68975. this._isEnabled = value;
  68976. if (value) {
  68977. this._scene.registerBeforeRender(this._renderFunction);
  68978. }
  68979. else {
  68980. this._scene.unregisterBeforeRender(this._renderFunction);
  68981. }
  68982. },
  68983. enumerable: true,
  68984. configurable: true
  68985. });
  68986. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  68987. if (x === void 0) { x = 0; }
  68988. if (y === void 0) { y = 0; }
  68989. if (z === void 0) { z = 0; }
  68990. var tmat = BABYLON.Tmp.Matrix[0];
  68991. var parentBone = bone.getParent();
  68992. tmat.copyFrom(bone.getLocalMatrix());
  68993. if (x !== 0 || y !== 0 || z !== 0) {
  68994. var tmat2 = BABYLON.Tmp.Matrix[1];
  68995. BABYLON.Matrix.IdentityToRef(tmat2);
  68996. tmat2.m[12] = x;
  68997. tmat2.m[13] = y;
  68998. tmat2.m[14] = z;
  68999. tmat2.multiplyToRef(tmat, tmat);
  69000. }
  69001. if (parentBone) {
  69002. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69003. }
  69004. tmat.multiplyToRef(meshMat, tmat);
  69005. position.x = tmat.m[12];
  69006. position.y = tmat.m[13];
  69007. position.z = tmat.m[14];
  69008. };
  69009. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69010. var len = bones.length;
  69011. var meshPos = this.mesh.position;
  69012. for (var i = 0; i < len; i++) {
  69013. var bone = bones[i];
  69014. var points = this._debugLines[i];
  69015. if (!points) {
  69016. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69017. this._debugLines[i] = points;
  69018. }
  69019. this._getBonePosition(points[0], bone, meshMat);
  69020. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69021. points[0].subtractInPlace(meshPos);
  69022. points[1].subtractInPlace(meshPos);
  69023. }
  69024. };
  69025. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69026. var len = bones.length;
  69027. var boneNum = 0;
  69028. var meshPos = this.mesh.position;
  69029. for (var i = len - 1; i >= 0; i--) {
  69030. var childBone = bones[i];
  69031. var parentBone = childBone.getParent();
  69032. if (!parentBone) {
  69033. continue;
  69034. }
  69035. var points = this._debugLines[boneNum];
  69036. if (!points) {
  69037. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69038. this._debugLines[boneNum] = points;
  69039. }
  69040. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69041. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69042. points[0].subtractInPlace(meshPos);
  69043. points[1].subtractInPlace(meshPos);
  69044. boneNum++;
  69045. }
  69046. };
  69047. SkeletonViewer.prototype.update = function () {
  69048. if (this.autoUpdateBonesMatrices) {
  69049. this.skeleton.computeAbsoluteTransforms();
  69050. }
  69051. if (this.skeleton.bones[0].length === undefined) {
  69052. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69053. }
  69054. else {
  69055. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69056. }
  69057. if (!this._debugMesh) {
  69058. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69059. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69060. }
  69061. else {
  69062. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69063. }
  69064. this._debugMesh.position.copyFrom(this.mesh.position);
  69065. this._debugMesh.color = this.color;
  69066. };
  69067. SkeletonViewer.prototype.dispose = function () {
  69068. if (this._debugMesh) {
  69069. this.isEnabled = false;
  69070. this._debugMesh.dispose();
  69071. this._debugMesh = null;
  69072. }
  69073. };
  69074. return SkeletonViewer;
  69075. }());
  69076. Debug.SkeletonViewer = SkeletonViewer;
  69077. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69078. })(BABYLON || (BABYLON = {}));
  69079. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69080. var BABYLON;
  69081. (function (BABYLON) {
  69082. var Debug;
  69083. (function (Debug) {
  69084. var AxesViewer = /** @class */ (function () {
  69085. function AxesViewer(scene, scaleLines) {
  69086. if (scaleLines === void 0) { scaleLines = 1; }
  69087. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69088. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69089. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69090. this.scaleLines = 1;
  69091. this.scaleLines = scaleLines;
  69092. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69093. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69094. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69095. this._xmesh.renderingGroupId = 2;
  69096. this._ymesh.renderingGroupId = 2;
  69097. this._zmesh.renderingGroupId = 2;
  69098. this._xmesh.material.checkReadyOnlyOnce = true;
  69099. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69100. this._ymesh.material.checkReadyOnlyOnce = true;
  69101. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69102. this._zmesh.material.checkReadyOnlyOnce = true;
  69103. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69104. this.scene = scene;
  69105. }
  69106. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69107. var scaleLines = this.scaleLines;
  69108. if (this._xmesh) {
  69109. this._xmesh.position.copyFrom(position);
  69110. }
  69111. if (this._ymesh) {
  69112. this._ymesh.position.copyFrom(position);
  69113. }
  69114. if (this._zmesh) {
  69115. this._zmesh.position.copyFrom(position);
  69116. }
  69117. var point2 = this._xline[1];
  69118. point2.x = xaxis.x * scaleLines;
  69119. point2.y = xaxis.y * scaleLines;
  69120. point2.z = xaxis.z * scaleLines;
  69121. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69122. point2 = this._yline[1];
  69123. point2.x = yaxis.x * scaleLines;
  69124. point2.y = yaxis.y * scaleLines;
  69125. point2.z = yaxis.z * scaleLines;
  69126. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69127. point2 = this._zline[1];
  69128. point2.x = zaxis.x * scaleLines;
  69129. point2.y = zaxis.y * scaleLines;
  69130. point2.z = zaxis.z * scaleLines;
  69131. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69132. };
  69133. AxesViewer.prototype.dispose = function () {
  69134. if (this._xmesh) {
  69135. this._xmesh.dispose();
  69136. }
  69137. if (this._ymesh) {
  69138. this._ymesh.dispose();
  69139. }
  69140. if (this._zmesh) {
  69141. this._zmesh.dispose();
  69142. }
  69143. this._xmesh = null;
  69144. this._ymesh = null;
  69145. this._zmesh = null;
  69146. this.scene = null;
  69147. };
  69148. return AxesViewer;
  69149. }());
  69150. Debug.AxesViewer = AxesViewer;
  69151. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69152. })(BABYLON || (BABYLON = {}));
  69153. //# sourceMappingURL=babylon.axesViewer.js.map
  69154. var BABYLON;
  69155. (function (BABYLON) {
  69156. var Debug;
  69157. (function (Debug) {
  69158. var BoneAxesViewer = /** @class */ (function (_super) {
  69159. __extends(BoneAxesViewer, _super);
  69160. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  69161. if (scaleLines === void 0) { scaleLines = 1; }
  69162. var _this = _super.call(this, scene, scaleLines) || this;
  69163. _this.pos = BABYLON.Vector3.Zero();
  69164. _this.xaxis = BABYLON.Vector3.Zero();
  69165. _this.yaxis = BABYLON.Vector3.Zero();
  69166. _this.zaxis = BABYLON.Vector3.Zero();
  69167. _this.mesh = mesh;
  69168. _this.bone = bone;
  69169. return _this;
  69170. }
  69171. BoneAxesViewer.prototype.update = function () {
  69172. if (!this.mesh || !this.bone) {
  69173. return;
  69174. }
  69175. var bone = this.bone;
  69176. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  69177. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  69178. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  69179. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  69180. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  69181. };
  69182. BoneAxesViewer.prototype.dispose = function () {
  69183. if (this.mesh) {
  69184. this.mesh = null;
  69185. this.bone = null;
  69186. _super.prototype.dispose.call(this);
  69187. }
  69188. };
  69189. return BoneAxesViewer;
  69190. }(Debug.AxesViewer));
  69191. Debug.BoneAxesViewer = BoneAxesViewer;
  69192. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69193. })(BABYLON || (BABYLON = {}));
  69194. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  69195. var BABYLON;
  69196. (function (BABYLON) {
  69197. var RayHelper = /** @class */ (function () {
  69198. function RayHelper(ray) {
  69199. this.ray = ray;
  69200. }
  69201. RayHelper.CreateAndShow = function (ray, scene, color) {
  69202. var helper = new RayHelper(ray);
  69203. helper.show(scene, color);
  69204. return helper;
  69205. };
  69206. RayHelper.prototype.show = function (scene, color) {
  69207. if (!this._renderFunction && this.ray) {
  69208. var ray = this.ray;
  69209. this._renderFunction = this._render.bind(this);
  69210. this._scene = scene;
  69211. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  69212. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  69213. if (this._renderFunction) {
  69214. this._scene.registerBeforeRender(this._renderFunction);
  69215. }
  69216. }
  69217. if (color && this._renderLine) {
  69218. this._renderLine.color.copyFrom(color);
  69219. }
  69220. };
  69221. RayHelper.prototype.hide = function () {
  69222. if (this._renderFunction && this._scene) {
  69223. this._scene.unregisterBeforeRender(this._renderFunction);
  69224. this._scene = null;
  69225. this._renderFunction = null;
  69226. if (this._renderLine) {
  69227. this._renderLine.dispose();
  69228. this._renderLine = null;
  69229. }
  69230. this._renderPoints = [];
  69231. }
  69232. };
  69233. RayHelper.prototype._render = function () {
  69234. var ray = this.ray;
  69235. if (!ray) {
  69236. return;
  69237. }
  69238. var point = this._renderPoints[1];
  69239. var len = Math.min(ray.length, 1000000);
  69240. point.copyFrom(ray.direction);
  69241. point.scaleInPlace(len);
  69242. point.addInPlace(ray.origin);
  69243. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  69244. };
  69245. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  69246. this._attachedToMesh = mesh;
  69247. var ray = this.ray;
  69248. if (!ray) {
  69249. return;
  69250. }
  69251. if (!ray.direction) {
  69252. ray.direction = BABYLON.Vector3.Zero();
  69253. }
  69254. if (!ray.origin) {
  69255. ray.origin = BABYLON.Vector3.Zero();
  69256. }
  69257. if (length) {
  69258. ray.length = length;
  69259. }
  69260. if (!meshSpaceOrigin) {
  69261. meshSpaceOrigin = BABYLON.Vector3.Zero();
  69262. }
  69263. if (!meshSpaceDirection) {
  69264. // -1 so that this will work with Mesh.lookAt
  69265. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  69266. }
  69267. if (!this._meshSpaceDirection) {
  69268. this._meshSpaceDirection = meshSpaceDirection.clone();
  69269. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  69270. }
  69271. else {
  69272. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  69273. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  69274. }
  69275. if (!this._updateToMeshFunction) {
  69276. this._updateToMeshFunction = this._updateToMesh.bind(this);
  69277. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  69278. }
  69279. this._updateToMesh();
  69280. };
  69281. RayHelper.prototype.detachFromMesh = function () {
  69282. if (this._attachedToMesh) {
  69283. if (this._updateToMeshFunction) {
  69284. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  69285. }
  69286. this._attachedToMesh = null;
  69287. this._updateToMeshFunction = null;
  69288. }
  69289. };
  69290. RayHelper.prototype._updateToMesh = function () {
  69291. var ray = this.ray;
  69292. if (!this._attachedToMesh || !ray) {
  69293. return;
  69294. }
  69295. if (this._attachedToMesh._isDisposed) {
  69296. this.detachFromMesh();
  69297. return;
  69298. }
  69299. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  69300. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  69301. };
  69302. RayHelper.prototype.dispose = function () {
  69303. this.hide();
  69304. this.detachFromMesh();
  69305. this.ray = null;
  69306. };
  69307. return RayHelper;
  69308. }());
  69309. BABYLON.RayHelper = RayHelper;
  69310. })(BABYLON || (BABYLON = {}));
  69311. //# sourceMappingURL=babylon.rayHelper.js.map
  69312. var BABYLON;
  69313. (function (BABYLON) {
  69314. // load the inspector using require, if not present in the global namespace.
  69315. var DebugLayer = /** @class */ (function () {
  69316. function DebugLayer(scene) {
  69317. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69318. this._scene = scene;
  69319. // load inspector using require, if it doesn't exist on the global namespace.
  69320. }
  69321. /** Creates the inspector window. */
  69322. DebugLayer.prototype._createInspector = function (config) {
  69323. if (config === void 0) { config = {}; }
  69324. var popup = config.popup || false;
  69325. var initialTab = config.initialTab || 0;
  69326. var parentElement = config.parentElement || null;
  69327. if (!this._inspector) {
  69328. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69329. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69330. } // else nothing to do,; instance is already existing
  69331. };
  69332. DebugLayer.prototype.isVisible = function () {
  69333. if (!this._inspector) {
  69334. return false;
  69335. }
  69336. return true;
  69337. };
  69338. DebugLayer.prototype.hide = function () {
  69339. if (this._inspector) {
  69340. try {
  69341. this._inspector.dispose();
  69342. }
  69343. catch (e) {
  69344. // If the inspector has been removed directly from the inspector tool
  69345. }
  69346. this._inspector = null;
  69347. }
  69348. };
  69349. DebugLayer.prototype.show = function (config) {
  69350. if (config === void 0) { config = {}; }
  69351. if (typeof this.BJSINSPECTOR == 'undefined') {
  69352. // Load inspector and add it to the DOM
  69353. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69354. }
  69355. else {
  69356. // Otherwise creates the inspector
  69357. this._createInspector(config);
  69358. }
  69359. };
  69360. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69361. return DebugLayer;
  69362. }());
  69363. BABYLON.DebugLayer = DebugLayer;
  69364. })(BABYLON || (BABYLON = {}));
  69365. //# sourceMappingURL=babylon.debugLayer.js.map
  69366. var BABYLON;
  69367. (function (BABYLON) {
  69368. var Debug;
  69369. (function (Debug) {
  69370. var PhysicsViewer = /** @class */ (function () {
  69371. function PhysicsViewer(scene) {
  69372. this._impostors = [];
  69373. this._meshes = [];
  69374. this._numMeshes = 0;
  69375. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69376. var physicEngine = this._scene.getPhysicsEngine();
  69377. if (physicEngine) {
  69378. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69379. }
  69380. }
  69381. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69382. var plugin = this._physicsEnginePlugin;
  69383. for (var i = 0; i < this._numMeshes; i++) {
  69384. var impostor = this._impostors[i];
  69385. if (!impostor) {
  69386. continue;
  69387. }
  69388. if (impostor.isDisposed) {
  69389. this.hideImpostor(this._impostors[i--]);
  69390. }
  69391. else {
  69392. var mesh = this._meshes[i];
  69393. if (mesh && plugin) {
  69394. plugin.syncMeshWithImpostor(mesh, impostor);
  69395. }
  69396. }
  69397. }
  69398. };
  69399. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69400. if (!this._scene) {
  69401. return;
  69402. }
  69403. for (var i = 0; i < this._numMeshes; i++) {
  69404. if (this._impostors[i] == impostor) {
  69405. return;
  69406. }
  69407. }
  69408. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69409. if (debugMesh) {
  69410. this._impostors[this._numMeshes] = impostor;
  69411. this._meshes[this._numMeshes] = debugMesh;
  69412. if (this._numMeshes === 0) {
  69413. this._renderFunction = this._updateDebugMeshes.bind(this);
  69414. this._scene.registerBeforeRender(this._renderFunction);
  69415. }
  69416. this._numMeshes++;
  69417. }
  69418. };
  69419. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69420. if (!impostor || !this._scene) {
  69421. return;
  69422. }
  69423. var removed = false;
  69424. for (var i = 0; i < this._numMeshes; i++) {
  69425. if (this._impostors[i] == impostor) {
  69426. var mesh = this._meshes[i];
  69427. if (!mesh) {
  69428. continue;
  69429. }
  69430. this._scene.removeMesh(mesh);
  69431. mesh.dispose();
  69432. this._numMeshes--;
  69433. if (this._numMeshes > 0) {
  69434. this._meshes[i] = this._meshes[this._numMeshes];
  69435. this._impostors[i] = this._impostors[this._numMeshes];
  69436. this._meshes[this._numMeshes] = null;
  69437. this._impostors[this._numMeshes] = null;
  69438. }
  69439. else {
  69440. this._meshes[0] = null;
  69441. this._impostors[0] = null;
  69442. }
  69443. removed = true;
  69444. break;
  69445. }
  69446. }
  69447. if (removed && this._numMeshes === 0) {
  69448. this._scene.unregisterBeforeRender(this._renderFunction);
  69449. }
  69450. };
  69451. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  69452. if (!this._debugMaterial) {
  69453. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  69454. this._debugMaterial.wireframe = true;
  69455. }
  69456. return this._debugMaterial;
  69457. };
  69458. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  69459. if (!this._debugBoxMesh) {
  69460. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  69461. this._debugBoxMesh.renderingGroupId = 1;
  69462. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69463. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  69464. scene.removeMesh(this._debugBoxMesh);
  69465. }
  69466. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  69467. };
  69468. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  69469. if (!this._debugSphereMesh) {
  69470. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  69471. this._debugSphereMesh.renderingGroupId = 1;
  69472. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69473. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  69474. scene.removeMesh(this._debugSphereMesh);
  69475. }
  69476. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  69477. };
  69478. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  69479. var mesh = null;
  69480. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  69481. mesh = this._getDebugBoxMesh(scene);
  69482. impostor.getBoxSizeToRef(mesh.scaling);
  69483. }
  69484. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  69485. mesh = this._getDebugSphereMesh(scene);
  69486. var radius = impostor.getRadius();
  69487. mesh.scaling.x = radius * 2;
  69488. mesh.scaling.y = radius * 2;
  69489. mesh.scaling.z = radius * 2;
  69490. }
  69491. return mesh;
  69492. };
  69493. PhysicsViewer.prototype.dispose = function () {
  69494. for (var i = 0; i < this._numMeshes; i++) {
  69495. this.hideImpostor(this._impostors[i]);
  69496. }
  69497. if (this._debugBoxMesh) {
  69498. this._debugBoxMesh.dispose();
  69499. }
  69500. if (this._debugSphereMesh) {
  69501. this._debugSphereMesh.dispose();
  69502. }
  69503. if (this._debugMaterial) {
  69504. this._debugMaterial.dispose();
  69505. }
  69506. this._impostors.length = 0;
  69507. this._scene = null;
  69508. this._physicsEnginePlugin = null;
  69509. };
  69510. return PhysicsViewer;
  69511. }());
  69512. Debug.PhysicsViewer = PhysicsViewer;
  69513. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69514. })(BABYLON || (BABYLON = {}));
  69515. //# sourceMappingURL=babylon.physicsViewer.js.map
  69516. var BABYLON;
  69517. (function (BABYLON) {
  69518. var BoundingBoxRenderer = /** @class */ (function () {
  69519. function BoundingBoxRenderer(scene) {
  69520. this.frontColor = new BABYLON.Color3(1, 1, 1);
  69521. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  69522. this.showBackLines = true;
  69523. this.renderList = new BABYLON.SmartArray(32);
  69524. this._vertexBuffers = {};
  69525. this._scene = scene;
  69526. }
  69527. BoundingBoxRenderer.prototype._prepareRessources = function () {
  69528. if (this._colorShader) {
  69529. return;
  69530. }
  69531. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  69532. attributes: [BABYLON.VertexBuffer.PositionKind],
  69533. uniforms: ["world", "viewProjection", "color"]
  69534. });
  69535. var engine = this._scene.getEngine();
  69536. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  69537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  69538. this._createIndexBuffer();
  69539. };
  69540. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  69541. var engine = this._scene.getEngine();
  69542. 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]);
  69543. };
  69544. BoundingBoxRenderer.prototype._rebuild = function () {
  69545. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69546. if (vb) {
  69547. vb._rebuild();
  69548. }
  69549. this._createIndexBuffer();
  69550. };
  69551. BoundingBoxRenderer.prototype.reset = function () {
  69552. this.renderList.reset();
  69553. };
  69554. BoundingBoxRenderer.prototype.render = function () {
  69555. if (this.renderList.length === 0) {
  69556. return;
  69557. }
  69558. this._prepareRessources();
  69559. if (!this._colorShader.isReady()) {
  69560. return;
  69561. }
  69562. var engine = this._scene.getEngine();
  69563. engine.setDepthWrite(false);
  69564. this._colorShader._preBind();
  69565. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  69566. var boundingBox = this.renderList.data[boundingBoxIndex];
  69567. var min = boundingBox.minimum;
  69568. var max = boundingBox.maximum;
  69569. var diff = max.subtract(min);
  69570. var median = min.add(diff.scale(0.5));
  69571. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69572. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69573. .multiply(boundingBox.getWorldMatrix());
  69574. // VBOs
  69575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69576. if (this.showBackLines) {
  69577. // Back
  69578. engine.setDepthFunctionToGreaterOrEqual();
  69579. this._scene.resetCachedMaterial();
  69580. this._colorShader.setColor4("color", this.backColor.toColor4());
  69581. this._colorShader.bind(worldMatrix);
  69582. // Draw order
  69583. engine.draw(false, 0, 24);
  69584. }
  69585. // Front
  69586. engine.setDepthFunctionToLess();
  69587. this._scene.resetCachedMaterial();
  69588. this._colorShader.setColor4("color", this.frontColor.toColor4());
  69589. this._colorShader.bind(worldMatrix);
  69590. // Draw order
  69591. engine.draw(false, 0, 24);
  69592. }
  69593. this._colorShader.unbind();
  69594. engine.setDepthFunctionToLessOrEqual();
  69595. engine.setDepthWrite(true);
  69596. };
  69597. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  69598. this._prepareRessources();
  69599. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  69600. return;
  69601. }
  69602. var engine = this._scene.getEngine();
  69603. engine.setDepthWrite(false);
  69604. engine.setColorWrite(false);
  69605. this._colorShader._preBind();
  69606. var boundingBox = mesh._boundingInfo.boundingBox;
  69607. var min = boundingBox.minimum;
  69608. var max = boundingBox.maximum;
  69609. var diff = max.subtract(min);
  69610. var median = min.add(diff.scale(0.5));
  69611. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69612. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69613. .multiply(boundingBox.getWorldMatrix());
  69614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69615. engine.setDepthFunctionToLess();
  69616. this._scene.resetCachedMaterial();
  69617. this._colorShader.bind(worldMatrix);
  69618. engine.draw(false, 0, 24);
  69619. this._colorShader.unbind();
  69620. engine.setDepthFunctionToLessOrEqual();
  69621. engine.setDepthWrite(true);
  69622. engine.setColorWrite(true);
  69623. };
  69624. BoundingBoxRenderer.prototype.dispose = function () {
  69625. if (!this._colorShader) {
  69626. return;
  69627. }
  69628. this.renderList.dispose();
  69629. this._colorShader.dispose();
  69630. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69631. if (buffer) {
  69632. buffer.dispose();
  69633. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69634. }
  69635. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69636. };
  69637. return BoundingBoxRenderer;
  69638. }());
  69639. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69640. })(BABYLON || (BABYLON = {}));
  69641. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69642. var BABYLON;
  69643. (function (BABYLON) {
  69644. var MorphTarget = /** @class */ (function () {
  69645. function MorphTarget(name, influence) {
  69646. if (influence === void 0) { influence = 0; }
  69647. this.name = name;
  69648. this.animations = new Array();
  69649. this._positions = null;
  69650. this._normals = null;
  69651. this._tangents = null;
  69652. this.onInfluenceChanged = new BABYLON.Observable();
  69653. this.influence = influence;
  69654. }
  69655. Object.defineProperty(MorphTarget.prototype, "influence", {
  69656. get: function () {
  69657. return this._influence;
  69658. },
  69659. set: function (influence) {
  69660. if (this._influence === influence) {
  69661. return;
  69662. }
  69663. var previous = this._influence;
  69664. this._influence = influence;
  69665. if (this.onInfluenceChanged.hasObservers) {
  69666. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69667. }
  69668. },
  69669. enumerable: true,
  69670. configurable: true
  69671. });
  69672. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69673. get: function () {
  69674. return !!this._positions;
  69675. },
  69676. enumerable: true,
  69677. configurable: true
  69678. });
  69679. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69680. get: function () {
  69681. return !!this._normals;
  69682. },
  69683. enumerable: true,
  69684. configurable: true
  69685. });
  69686. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69687. get: function () {
  69688. return !!this._tangents;
  69689. },
  69690. enumerable: true,
  69691. configurable: true
  69692. });
  69693. MorphTarget.prototype.setPositions = function (data) {
  69694. this._positions = data;
  69695. };
  69696. MorphTarget.prototype.getPositions = function () {
  69697. return this._positions;
  69698. };
  69699. MorphTarget.prototype.setNormals = function (data) {
  69700. this._normals = data;
  69701. };
  69702. MorphTarget.prototype.getNormals = function () {
  69703. return this._normals;
  69704. };
  69705. MorphTarget.prototype.setTangents = function (data) {
  69706. this._tangents = data;
  69707. };
  69708. MorphTarget.prototype.getTangents = function () {
  69709. return this._tangents;
  69710. };
  69711. /**
  69712. * Serializes the current target into a Serialization object.
  69713. * Returns the serialized object.
  69714. */
  69715. MorphTarget.prototype.serialize = function () {
  69716. var serializationObject = {};
  69717. serializationObject.name = this.name;
  69718. serializationObject.influence = this.influence;
  69719. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69720. if (this.hasNormals) {
  69721. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69722. }
  69723. if (this.hasTangents) {
  69724. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69725. }
  69726. // Animations
  69727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69728. return serializationObject;
  69729. };
  69730. // Statics
  69731. MorphTarget.Parse = function (serializationObject) {
  69732. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69733. result.setPositions(serializationObject.positions);
  69734. if (serializationObject.normals) {
  69735. result.setNormals(serializationObject.normals);
  69736. }
  69737. if (serializationObject.tangents) {
  69738. result.setTangents(serializationObject.tangents);
  69739. }
  69740. // Animations
  69741. if (serializationObject.animations) {
  69742. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69743. var parsedAnimation = serializationObject.animations[animationIndex];
  69744. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69745. }
  69746. }
  69747. return result;
  69748. };
  69749. MorphTarget.FromMesh = function (mesh, name, influence) {
  69750. if (!name) {
  69751. name = mesh.name;
  69752. }
  69753. var result = new MorphTarget(name, influence);
  69754. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69756. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69757. }
  69758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69759. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69760. }
  69761. return result;
  69762. };
  69763. return MorphTarget;
  69764. }());
  69765. BABYLON.MorphTarget = MorphTarget;
  69766. })(BABYLON || (BABYLON = {}));
  69767. //# sourceMappingURL=babylon.morphTarget.js.map
  69768. var BABYLON;
  69769. (function (BABYLON) {
  69770. var MorphTargetManager = /** @class */ (function () {
  69771. function MorphTargetManager(scene) {
  69772. if (scene === void 0) { scene = null; }
  69773. this._targets = new Array();
  69774. this._targetObservable = new Array();
  69775. this._activeTargets = new BABYLON.SmartArray(16);
  69776. this._supportsNormals = false;
  69777. this._supportsTangents = false;
  69778. this._vertexCount = 0;
  69779. this._uniqueId = 0;
  69780. this._tempInfluences = new Array();
  69781. if (!scene) {
  69782. scene = BABYLON.Engine.LastCreatedScene;
  69783. }
  69784. this._scene = scene;
  69785. if (this._scene) {
  69786. this._scene.morphTargetManagers.push(this);
  69787. this._uniqueId = this._scene.getUniqueId();
  69788. }
  69789. }
  69790. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69791. get: function () {
  69792. return this._uniqueId;
  69793. },
  69794. enumerable: true,
  69795. configurable: true
  69796. });
  69797. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69798. get: function () {
  69799. return this._vertexCount;
  69800. },
  69801. enumerable: true,
  69802. configurable: true
  69803. });
  69804. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69805. get: function () {
  69806. return this._supportsNormals;
  69807. },
  69808. enumerable: true,
  69809. configurable: true
  69810. });
  69811. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69812. get: function () {
  69813. return this._supportsTangents;
  69814. },
  69815. enumerable: true,
  69816. configurable: true
  69817. });
  69818. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69819. get: function () {
  69820. return this._targets.length;
  69821. },
  69822. enumerable: true,
  69823. configurable: true
  69824. });
  69825. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69826. get: function () {
  69827. return this._activeTargets.length;
  69828. },
  69829. enumerable: true,
  69830. configurable: true
  69831. });
  69832. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69833. get: function () {
  69834. return this._influences;
  69835. },
  69836. enumerable: true,
  69837. configurable: true
  69838. });
  69839. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69840. return this._activeTargets.data[index];
  69841. };
  69842. MorphTargetManager.prototype.getTarget = function (index) {
  69843. return this._targets[index];
  69844. };
  69845. MorphTargetManager.prototype.addTarget = function (target) {
  69846. var _this = this;
  69847. this._targets.push(target);
  69848. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69849. _this._syncActiveTargets(needUpdate);
  69850. }));
  69851. this._syncActiveTargets(true);
  69852. };
  69853. MorphTargetManager.prototype.removeTarget = function (target) {
  69854. var index = this._targets.indexOf(target);
  69855. if (index >= 0) {
  69856. this._targets.splice(index, 1);
  69857. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69858. this._syncActiveTargets(true);
  69859. }
  69860. };
  69861. /**
  69862. * Serializes the current manager into a Serialization object.
  69863. * Returns the serialized object.
  69864. */
  69865. MorphTargetManager.prototype.serialize = function () {
  69866. var serializationObject = {};
  69867. serializationObject.id = this.uniqueId;
  69868. serializationObject.targets = [];
  69869. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69870. var target = _a[_i];
  69871. serializationObject.targets.push(target.serialize());
  69872. }
  69873. return serializationObject;
  69874. };
  69875. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69876. var influenceCount = 0;
  69877. this._activeTargets.reset();
  69878. this._supportsNormals = true;
  69879. this._supportsTangents = true;
  69880. this._vertexCount = 0;
  69881. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69882. var target = _a[_i];
  69883. if (target.influence > 0) {
  69884. this._activeTargets.push(target);
  69885. this._tempInfluences[influenceCount++] = target.influence;
  69886. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69887. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69888. var positions = target.getPositions();
  69889. if (!positions) {
  69890. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69891. return;
  69892. }
  69893. var vertexCount = positions.length / 3;
  69894. if (this._vertexCount === 0) {
  69895. this._vertexCount = vertexCount;
  69896. }
  69897. else if (this._vertexCount !== vertexCount) {
  69898. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  69899. return;
  69900. }
  69901. }
  69902. }
  69903. if (!this._influences || this._influences.length !== influenceCount) {
  69904. this._influences = new Float32Array(influenceCount);
  69905. }
  69906. for (var index = 0; index < influenceCount; index++) {
  69907. this._influences[index] = this._tempInfluences[index];
  69908. }
  69909. if (needUpdate && this._scene) {
  69910. // Flag meshes as dirty to resync with the active targets
  69911. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  69912. var mesh = _c[_b];
  69913. if (mesh.morphTargetManager === this) {
  69914. mesh._syncGeometryWithMorphTargetManager();
  69915. }
  69916. }
  69917. }
  69918. };
  69919. // Statics
  69920. MorphTargetManager.Parse = function (serializationObject, scene) {
  69921. var result = new MorphTargetManager(scene);
  69922. result._uniqueId = serializationObject.id;
  69923. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  69924. var targetData = _a[_i];
  69925. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  69926. }
  69927. return result;
  69928. };
  69929. return MorphTargetManager;
  69930. }());
  69931. BABYLON.MorphTargetManager = MorphTargetManager;
  69932. })(BABYLON || (BABYLON = {}));
  69933. //# sourceMappingURL=babylon.morphTargetManager.js.map
  69934. var BABYLON;
  69935. (function (BABYLON) {
  69936. var Octree = /** @class */ (function () {
  69937. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  69938. if (maxDepth === void 0) { maxDepth = 2; }
  69939. this.maxDepth = maxDepth;
  69940. this.dynamicContent = new Array();
  69941. this._maxBlockCapacity = maxBlockCapacity || 64;
  69942. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  69943. this._creationFunc = creationFunc;
  69944. }
  69945. // Methods
  69946. Octree.prototype.update = function (worldMin, worldMax, entries) {
  69947. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  69948. };
  69949. Octree.prototype.addMesh = function (entry) {
  69950. for (var index = 0; index < this.blocks.length; index++) {
  69951. var block = this.blocks[index];
  69952. block.addEntry(entry);
  69953. }
  69954. };
  69955. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  69956. this._selectionContent.reset();
  69957. for (var index = 0; index < this.blocks.length; index++) {
  69958. var block = this.blocks[index];
  69959. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  69960. }
  69961. if (allowDuplicate) {
  69962. this._selectionContent.concat(this.dynamicContent);
  69963. }
  69964. else {
  69965. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69966. }
  69967. return this._selectionContent;
  69968. };
  69969. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  69970. this._selectionContent.reset();
  69971. for (var index = 0; index < this.blocks.length; index++) {
  69972. var block = this.blocks[index];
  69973. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  69974. }
  69975. if (allowDuplicate) {
  69976. this._selectionContent.concat(this.dynamicContent);
  69977. }
  69978. else {
  69979. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69980. }
  69981. return this._selectionContent;
  69982. };
  69983. Octree.prototype.intersectsRay = function (ray) {
  69984. this._selectionContent.reset();
  69985. for (var index = 0; index < this.blocks.length; index++) {
  69986. var block = this.blocks[index];
  69987. block.intersectsRay(ray, this._selectionContent);
  69988. }
  69989. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69990. return this._selectionContent;
  69991. };
  69992. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  69993. target.blocks = new Array();
  69994. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  69995. // Segmenting space
  69996. for (var x = 0; x < 2; x++) {
  69997. for (var y = 0; y < 2; y++) {
  69998. for (var z = 0; z < 2; z++) {
  69999. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70000. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70001. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70002. block.addEntries(entries);
  70003. target.blocks.push(block);
  70004. }
  70005. }
  70006. }
  70007. };
  70008. Octree.CreationFuncForMeshes = function (entry, block) {
  70009. var boundingInfo = entry.getBoundingInfo();
  70010. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70011. block.entries.push(entry);
  70012. }
  70013. };
  70014. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70015. var boundingInfo = entry.getBoundingInfo();
  70016. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70017. block.entries.push(entry);
  70018. }
  70019. };
  70020. return Octree;
  70021. }());
  70022. BABYLON.Octree = Octree;
  70023. })(BABYLON || (BABYLON = {}));
  70024. //# sourceMappingURL=babylon.octree.js.map
  70025. var BABYLON;
  70026. (function (BABYLON) {
  70027. var OctreeBlock = /** @class */ (function () {
  70028. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70029. this.entries = new Array();
  70030. this._boundingVectors = new Array();
  70031. this._capacity = capacity;
  70032. this._depth = depth;
  70033. this._maxDepth = maxDepth;
  70034. this._creationFunc = creationFunc;
  70035. this._minPoint = minPoint;
  70036. this._maxPoint = maxPoint;
  70037. this._boundingVectors.push(minPoint.clone());
  70038. this._boundingVectors.push(maxPoint.clone());
  70039. this._boundingVectors.push(minPoint.clone());
  70040. this._boundingVectors[2].x = maxPoint.x;
  70041. this._boundingVectors.push(minPoint.clone());
  70042. this._boundingVectors[3].y = maxPoint.y;
  70043. this._boundingVectors.push(minPoint.clone());
  70044. this._boundingVectors[4].z = maxPoint.z;
  70045. this._boundingVectors.push(maxPoint.clone());
  70046. this._boundingVectors[5].z = minPoint.z;
  70047. this._boundingVectors.push(maxPoint.clone());
  70048. this._boundingVectors[6].x = minPoint.x;
  70049. this._boundingVectors.push(maxPoint.clone());
  70050. this._boundingVectors[7].y = minPoint.y;
  70051. }
  70052. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70053. // Property
  70054. get: function () {
  70055. return this._capacity;
  70056. },
  70057. enumerable: true,
  70058. configurable: true
  70059. });
  70060. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70061. get: function () {
  70062. return this._minPoint;
  70063. },
  70064. enumerable: true,
  70065. configurable: true
  70066. });
  70067. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70068. get: function () {
  70069. return this._maxPoint;
  70070. },
  70071. enumerable: true,
  70072. configurable: true
  70073. });
  70074. // Methods
  70075. OctreeBlock.prototype.addEntry = function (entry) {
  70076. if (this.blocks) {
  70077. for (var index = 0; index < this.blocks.length; index++) {
  70078. var block = this.blocks[index];
  70079. block.addEntry(entry);
  70080. }
  70081. return;
  70082. }
  70083. this._creationFunc(entry, this);
  70084. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70085. this.createInnerBlocks();
  70086. }
  70087. };
  70088. OctreeBlock.prototype.addEntries = function (entries) {
  70089. for (var index = 0; index < entries.length; index++) {
  70090. var mesh = entries[index];
  70091. this.addEntry(mesh);
  70092. }
  70093. };
  70094. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70095. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70096. if (this.blocks) {
  70097. for (var index = 0; index < this.blocks.length; index++) {
  70098. var block = this.blocks[index];
  70099. block.select(frustumPlanes, selection, allowDuplicate);
  70100. }
  70101. return;
  70102. }
  70103. if (allowDuplicate) {
  70104. selection.concat(this.entries);
  70105. }
  70106. else {
  70107. selection.concatWithNoDuplicate(this.entries);
  70108. }
  70109. }
  70110. };
  70111. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70112. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70113. if (this.blocks) {
  70114. for (var index = 0; index < this.blocks.length; index++) {
  70115. var block = this.blocks[index];
  70116. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70117. }
  70118. return;
  70119. }
  70120. if (allowDuplicate) {
  70121. selection.concat(this.entries);
  70122. }
  70123. else {
  70124. selection.concatWithNoDuplicate(this.entries);
  70125. }
  70126. }
  70127. };
  70128. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70129. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70130. if (this.blocks) {
  70131. for (var index = 0; index < this.blocks.length; index++) {
  70132. var block = this.blocks[index];
  70133. block.intersectsRay(ray, selection);
  70134. }
  70135. return;
  70136. }
  70137. selection.concatWithNoDuplicate(this.entries);
  70138. }
  70139. };
  70140. OctreeBlock.prototype.createInnerBlocks = function () {
  70141. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  70142. };
  70143. return OctreeBlock;
  70144. }());
  70145. BABYLON.OctreeBlock = OctreeBlock;
  70146. })(BABYLON || (BABYLON = {}));
  70147. //# sourceMappingURL=babylon.octreeBlock.js.map
  70148. var BABYLON;
  70149. (function (BABYLON) {
  70150. var SIMDVector3 = /** @class */ (function () {
  70151. function SIMDVector3() {
  70152. }
  70153. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  70154. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  70155. };
  70156. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  70157. var m = transformation.m;
  70158. var m0 = SIMD.Float32x4.load(m, 0);
  70159. var m1 = SIMD.Float32x4.load(m, 4);
  70160. var m2 = SIMD.Float32x4.load(m, 8);
  70161. var m3 = SIMD.Float32x4.load(m, 12);
  70162. 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));
  70163. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  70164. result.x = SIMD.Float32x4.extractLane(r, 0);
  70165. result.y = SIMD.Float32x4.extractLane(r, 1);
  70166. result.z = SIMD.Float32x4.extractLane(r, 2);
  70167. };
  70168. return SIMDVector3;
  70169. }());
  70170. var SIMDMatrix = /** @class */ (function () {
  70171. function SIMDMatrix() {
  70172. }
  70173. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  70174. var tm = this.m;
  70175. var om = other.m;
  70176. var m0 = SIMD.Float32x4.load(om, 0);
  70177. var m1 = SIMD.Float32x4.load(om, 4);
  70178. var m2 = SIMD.Float32x4.load(om, 8);
  70179. var m3 = SIMD.Float32x4.load(om, 12);
  70180. for (var i = 0; i < 16; i += 4) {
  70181. 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)))));
  70182. }
  70183. return this;
  70184. };
  70185. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  70186. var src = this.m;
  70187. var dest = other.m;
  70188. // Load the 4 rows
  70189. var src0 = SIMD.Float32x4.load(src, 0);
  70190. var src1 = SIMD.Float32x4.load(src, 4);
  70191. var src2 = SIMD.Float32x4.load(src, 8);
  70192. var src3 = SIMD.Float32x4.load(src, 12);
  70193. // Transpose the source matrix. Sort of. Not a true transpose operation
  70194. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  70195. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  70196. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  70197. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  70198. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  70199. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  70200. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  70201. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  70202. // This is a true transposition, but it will lead to an incorrect result
  70203. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  70204. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  70205. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70206. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70207. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  70208. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  70209. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70210. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70211. // ----
  70212. tmp1 = SIMD.Float32x4.mul(row2, row3);
  70213. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70214. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  70215. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  70216. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70217. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  70218. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  70219. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  70220. // ----
  70221. tmp1 = SIMD.Float32x4.mul(row1, row2);
  70222. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70223. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  70224. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  70225. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70226. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  70227. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  70228. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  70229. // ----
  70230. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  70231. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70232. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  70233. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  70234. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  70235. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70236. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  70237. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  70238. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  70239. // ----
  70240. tmp1 = SIMD.Float32x4.mul(row0, row1);
  70241. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70242. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70243. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  70244. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70245. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70246. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  70247. // ----
  70248. tmp1 = SIMD.Float32x4.mul(row0, row3);
  70249. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70250. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  70251. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  70252. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70253. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  70254. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  70255. // ----
  70256. tmp1 = SIMD.Float32x4.mul(row0, row2);
  70257. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70258. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  70259. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  70260. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70261. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  70262. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  70263. // Compute determinant
  70264. var det = SIMD.Float32x4.mul(row0, minor0);
  70265. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  70266. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  70267. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  70268. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  70269. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  70270. // These shuffles aren't necessary if the faulty transposition is done
  70271. // up at the top of this function.
  70272. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  70273. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  70274. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  70275. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  70276. // Compute final values by multiplying with 1/det
  70277. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  70278. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  70279. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  70280. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  70281. return this;
  70282. };
  70283. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  70284. var out = result.m;
  70285. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  70286. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  70287. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  70288. // cc.kmVec3Subtract(f, pCenter, pEye);
  70289. var f = SIMD.Float32x4.sub(center, eye);
  70290. // cc.kmVec3Normalize(f, f);
  70291. var tmp = SIMD.Float32x4.mul(f, f);
  70292. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70293. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70294. // cc.kmVec3Assign(up, pUp);
  70295. // cc.kmVec3Normalize(up, up);
  70296. tmp = SIMD.Float32x4.mul(up, up);
  70297. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70298. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70299. // cc.kmVec3Cross(s, f, up);
  70300. 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)));
  70301. // cc.kmVec3Normalize(s, s);
  70302. tmp = SIMD.Float32x4.mul(s, s);
  70303. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70304. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70305. // cc.kmVec3Cross(u, s, f);
  70306. 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)));
  70307. // cc.kmVec3Normalize(s, s);
  70308. tmp = SIMD.Float32x4.mul(s, s);
  70309. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70310. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70311. var zero = SIMD.Float32x4.splat(0.0);
  70312. s = SIMD.Float32x4.neg(s);
  70313. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70314. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70315. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70316. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70317. 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);
  70318. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70319. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70320. 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)))));
  70321. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70322. 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)))));
  70323. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70324. 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)))));
  70325. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70326. 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)))));
  70327. };
  70328. return SIMDMatrix;
  70329. }());
  70330. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70331. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70332. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70333. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70334. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70335. var SIMDHelper = /** @class */ (function () {
  70336. function SIMDHelper() {
  70337. }
  70338. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70339. get: function () {
  70340. return SIMDHelper._isEnabled;
  70341. },
  70342. enumerable: true,
  70343. configurable: true
  70344. });
  70345. SIMDHelper.DisableSIMD = function () {
  70346. // Replace functions
  70347. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70348. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70349. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70350. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70351. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70352. SIMDHelper._isEnabled = false;
  70353. };
  70354. SIMDHelper.EnableSIMD = function () {
  70355. if (self.SIMD === undefined) {
  70356. return;
  70357. }
  70358. // check if polyfills needed
  70359. if (!self.Math.fround) {
  70360. self.Math.fround = (function (array) { return function (x) {
  70361. return array[0] = x, array[0];
  70362. }; })(new Float32Array(1));
  70363. }
  70364. if (!self.Math.imul) {
  70365. self.Math.imul = function (a, b) {
  70366. var ah = (a >>> 16) & 0xffff;
  70367. var al = a & 0xffff;
  70368. var bh = (b >>> 16) & 0xffff;
  70369. var bl = b & 0xffff;
  70370. // the shift by 0 fixes the sign on the high part
  70371. // the final |0 converts the unsigned value into a signed value
  70372. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70373. };
  70374. }
  70375. // Replace functions
  70376. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70377. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70378. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70379. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70380. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70381. SIMDHelper._isEnabled = true;
  70382. };
  70383. SIMDHelper._isEnabled = false;
  70384. return SIMDHelper;
  70385. }());
  70386. BABYLON.SIMDHelper = SIMDHelper;
  70387. })(BABYLON || (BABYLON = {}));
  70388. //# sourceMappingURL=babylon.math.SIMD.js.map
  70389. var BABYLON;
  70390. (function (BABYLON) {
  70391. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70392. __extends(VRDistortionCorrectionPostProcess, _super);
  70393. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70394. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70395. 'LensCenter',
  70396. 'Scale',
  70397. 'ScaleIn',
  70398. 'HmdWarpParam'
  70399. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70400. _this._isRightEye = isRightEye;
  70401. _this._distortionFactors = vrMetrics.distortionK;
  70402. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70403. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70404. _this.adaptScaleToCurrentViewport = true;
  70405. _this.onSizeChangedObservable.add(function () {
  70406. _this.aspectRatio = _this.width * .5 / _this.height;
  70407. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70408. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70409. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70410. });
  70411. _this.onApplyObservable.add(function (effect) {
  70412. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70413. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70414. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70415. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70416. });
  70417. return _this;
  70418. }
  70419. return VRDistortionCorrectionPostProcess;
  70420. }(BABYLON.PostProcess));
  70421. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70422. })(BABYLON || (BABYLON = {}));
  70423. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  70424. var BABYLON;
  70425. (function (BABYLON) {
  70426. var AnaglyphPostProcess = /** @class */ (function (_super) {
  70427. __extends(AnaglyphPostProcess, _super);
  70428. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  70429. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  70430. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70431. _this.onApplyObservable.add(function (effect) {
  70432. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  70433. });
  70434. return _this;
  70435. }
  70436. return AnaglyphPostProcess;
  70437. }(BABYLON.PostProcess));
  70438. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  70439. })(BABYLON || (BABYLON = {}));
  70440. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  70441. var BABYLON;
  70442. (function (BABYLON) {
  70443. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  70444. __extends(StereoscopicInterlacePostProcess, _super);
  70445. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  70446. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  70447. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70448. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70449. _this.onSizeChangedObservable.add(function () {
  70450. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70451. });
  70452. _this.onApplyObservable.add(function (effect) {
  70453. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  70454. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  70455. });
  70456. return _this;
  70457. }
  70458. return StereoscopicInterlacePostProcess;
  70459. }(BABYLON.PostProcess));
  70460. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  70461. })(BABYLON || (BABYLON = {}));
  70462. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  70463. var BABYLON;
  70464. (function (BABYLON) {
  70465. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  70466. function FreeCameraDeviceOrientationInput() {
  70467. var _this = this;
  70468. this._screenOrientationAngle = 0;
  70469. this._screenQuaternion = new BABYLON.Quaternion();
  70470. this._alpha = 0;
  70471. this._beta = 0;
  70472. this._gamma = 0;
  70473. this._orientationChanged = function () {
  70474. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  70475. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  70476. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  70477. };
  70478. this._deviceOrientation = function (evt) {
  70479. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  70480. _this._beta = evt.beta !== null ? evt.beta : 0;
  70481. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  70482. };
  70483. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  70484. this._orientationChanged();
  70485. }
  70486. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  70487. get: function () {
  70488. return this._camera;
  70489. },
  70490. set: function (camera) {
  70491. this._camera = camera;
  70492. if (this._camera != null && !this._camera.rotationQuaternion) {
  70493. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  70494. }
  70495. },
  70496. enumerable: true,
  70497. configurable: true
  70498. });
  70499. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70500. window.addEventListener("orientationchange", this._orientationChanged);
  70501. window.addEventListener("deviceorientation", this._deviceOrientation);
  70502. //In certain cases, the attach control is called AFTER orientation was changed,
  70503. //So this is needed.
  70504. this._orientationChanged();
  70505. };
  70506. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  70507. window.removeEventListener("orientationchange", this._orientationChanged);
  70508. window.removeEventListener("deviceorientation", this._deviceOrientation);
  70509. };
  70510. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  70511. //if no device orientation provided, don't update the rotation.
  70512. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  70513. if (!this._alpha)
  70514. return;
  70515. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  70516. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  70517. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  70518. //Mirror on XY Plane
  70519. this._camera.rotationQuaternion.z *= -1;
  70520. this._camera.rotationQuaternion.w *= -1;
  70521. };
  70522. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  70523. return "FreeCameraDeviceOrientationInput";
  70524. };
  70525. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  70526. return "deviceOrientation";
  70527. };
  70528. return FreeCameraDeviceOrientationInput;
  70529. }());
  70530. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  70531. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  70532. })(BABYLON || (BABYLON = {}));
  70533. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  70534. var BABYLON;
  70535. (function (BABYLON) {
  70536. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  70537. function ArcRotateCameraVRDeviceOrientationInput() {
  70538. this.alphaCorrection = 1;
  70539. this.betaCorrection = 1;
  70540. this.gammaCorrection = 1;
  70541. this._alpha = 0;
  70542. this._gamma = 0;
  70543. this._dirty = false;
  70544. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  70545. }
  70546. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70547. this.camera.attachControl(element, noPreventDefault);
  70548. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  70549. };
  70550. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  70551. if (evt.alpha !== null) {
  70552. this._alpha = +evt.alpha | 0;
  70553. }
  70554. if (evt.gamma !== null) {
  70555. this._gamma = +evt.gamma | 0;
  70556. }
  70557. this._dirty = true;
  70558. };
  70559. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  70560. if (this._dirty) {
  70561. this._dirty = false;
  70562. if (this._gamma < 0) {
  70563. this._gamma = 180 + this._gamma;
  70564. }
  70565. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  70566. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  70567. }
  70568. };
  70569. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  70570. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  70571. };
  70572. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  70573. return "ArcRotateCameraVRDeviceOrientationInput";
  70574. };
  70575. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  70576. return "VRDeviceOrientation";
  70577. };
  70578. return ArcRotateCameraVRDeviceOrientationInput;
  70579. }());
  70580. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  70581. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  70582. })(BABYLON || (BABYLON = {}));
  70583. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  70584. var BABYLON;
  70585. (function (BABYLON) {
  70586. var VRCameraMetrics = /** @class */ (function () {
  70587. function VRCameraMetrics() {
  70588. this.compensateDistortion = true;
  70589. }
  70590. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  70591. get: function () {
  70592. return this.hResolution / (2 * this.vResolution);
  70593. },
  70594. enumerable: true,
  70595. configurable: true
  70596. });
  70597. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  70598. get: function () {
  70599. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  70605. get: function () {
  70606. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70607. var h = (4 * meters) / this.hScreenSize;
  70608. return BABYLON.Matrix.Translation(h, 0, 0);
  70609. },
  70610. enumerable: true,
  70611. configurable: true
  70612. });
  70613. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  70614. get: function () {
  70615. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70616. var h = (4 * meters) / this.hScreenSize;
  70617. return BABYLON.Matrix.Translation(-h, 0, 0);
  70618. },
  70619. enumerable: true,
  70620. configurable: true
  70621. });
  70622. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70623. get: function () {
  70624. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70625. },
  70626. enumerable: true,
  70627. configurable: true
  70628. });
  70629. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70630. get: function () {
  70631. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70632. },
  70633. enumerable: true,
  70634. configurable: true
  70635. });
  70636. VRCameraMetrics.GetDefault = function () {
  70637. var result = new VRCameraMetrics();
  70638. result.hResolution = 1280;
  70639. result.vResolution = 800;
  70640. result.hScreenSize = 0.149759993;
  70641. result.vScreenSize = 0.0935999975;
  70642. result.vScreenCenter = 0.0467999987;
  70643. result.eyeToScreenDistance = 0.0410000011;
  70644. result.lensSeparationDistance = 0.0635000020;
  70645. result.interpupillaryDistance = 0.0640000030;
  70646. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70647. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70648. result.postProcessScaleFactor = 1.714605507808412;
  70649. result.lensCenterOffset = 0.151976421;
  70650. return result;
  70651. };
  70652. return VRCameraMetrics;
  70653. }());
  70654. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70655. })(BABYLON || (BABYLON = {}));
  70656. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70657. var BABYLON;
  70658. (function (BABYLON) {
  70659. var WebVRFreeCamera = /** @class */ (function (_super) {
  70660. __extends(WebVRFreeCamera, _super);
  70661. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70662. if (webVROptions === void 0) { webVROptions = {}; }
  70663. var _this = _super.call(this, name, position, scene) || this;
  70664. _this.webVROptions = webVROptions;
  70665. _this._vrDevice = null;
  70666. _this.rawPose = null;
  70667. _this._specsVersion = "1.1";
  70668. _this._attached = false;
  70669. _this._descendants = [];
  70670. _this.devicePosition = BABYLON.Vector3.Zero();
  70671. _this.deviceScaleFactor = 1;
  70672. _this.controllers = [];
  70673. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70674. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70675. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70676. if (webVROptions.defaultHeight) {
  70677. _this.position.y = webVROptions.defaultHeight;
  70678. }
  70679. _this.minZ = 0.1;
  70680. //legacy support - the compensation boolean was removed.
  70681. if (arguments.length === 5) {
  70682. _this.webVROptions = arguments[4];
  70683. }
  70684. // default webVR options
  70685. if (_this.webVROptions.trackPosition == undefined) {
  70686. _this.webVROptions.trackPosition = true;
  70687. }
  70688. if (_this.webVROptions.controllerMeshes == undefined) {
  70689. _this.webVROptions.controllerMeshes = true;
  70690. }
  70691. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70692. _this.webVROptions.defaultLightingOnControllers = true;
  70693. }
  70694. _this.rotationQuaternion = new BABYLON.Quaternion();
  70695. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70696. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70697. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70698. }
  70699. //enable VR
  70700. var engine = _this.getEngine();
  70701. _this._onVREnabled = function (success) { if (success) {
  70702. _this.initControllers();
  70703. } };
  70704. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70705. engine.initWebVR().add(function (event) {
  70706. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70707. return;
  70708. }
  70709. _this._vrDevice = event.vrDisplay;
  70710. //reset the rig parameters.
  70711. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70712. if (_this._attached) {
  70713. _this.getEngine().enableVR();
  70714. }
  70715. });
  70716. if (typeof (VRFrameData) !== "undefined")
  70717. _this._frameData = new VRFrameData();
  70718. /**
  70719. * The idea behind the following lines:
  70720. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70721. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70722. * the second will not show it correctly.
  70723. *
  70724. * To solve this - each object that has the camera as parent will be added to a protected array.
  70725. * When the rig camera renders, it will take this array and set all of those to be its children.
  70726. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70727. * Amazing!
  70728. */
  70729. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70730. if (camera.parent === _this && _this.rigParenting) {
  70731. _this._descendants = _this.getDescendants(true, function (n) {
  70732. // don't take the cameras or the controllers!
  70733. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70734. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70735. return !isController && !isRigCamera;
  70736. });
  70737. _this._descendants.forEach(function (node) {
  70738. node.parent = camera;
  70739. });
  70740. }
  70741. });
  70742. scene.onAfterCameraRenderObservable.add(function (camera) {
  70743. if (camera.parent === _this && _this.rigParenting) {
  70744. _this._descendants.forEach(function (node) {
  70745. node.parent = _this;
  70746. });
  70747. }
  70748. });
  70749. return _this;
  70750. }
  70751. WebVRFreeCamera.prototype.dispose = function () {
  70752. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70753. _super.prototype.dispose.call(this);
  70754. };
  70755. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70756. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70757. var gp = _a[_i];
  70758. if (gp.hand === name) {
  70759. return gp;
  70760. }
  70761. }
  70762. return null;
  70763. };
  70764. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70765. get: function () {
  70766. if (!this._leftController) {
  70767. this._leftController = this.getControllerByName("left");
  70768. }
  70769. return this._leftController;
  70770. },
  70771. enumerable: true,
  70772. configurable: true
  70773. });
  70774. ;
  70775. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70776. get: function () {
  70777. if (!this._rightController) {
  70778. this._rightController = this.getControllerByName("right");
  70779. }
  70780. return this._rightController;
  70781. },
  70782. enumerable: true,
  70783. configurable: true
  70784. });
  70785. ;
  70786. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70787. if (length === void 0) { length = 100; }
  70788. if (this.leftCamera) {
  70789. // Use left eye to avoid computation to compute center on every call
  70790. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  70791. }
  70792. else {
  70793. return _super.prototype.getForwardRay.call(this, length);
  70794. }
  70795. };
  70796. WebVRFreeCamera.prototype._checkInputs = function () {
  70797. if (this._vrDevice && this._vrDevice.isPresenting) {
  70798. this._vrDevice.getFrameData(this._frameData);
  70799. this.updateFromDevice(this._frameData.pose);
  70800. }
  70801. _super.prototype._checkInputs.call(this);
  70802. };
  70803. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70804. if (poseData && poseData.orientation) {
  70805. this.rawPose = poseData;
  70806. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70807. if (this.getScene().useRightHandedSystem) {
  70808. this.deviceRotationQuaternion.z *= -1;
  70809. this.deviceRotationQuaternion.w *= -1;
  70810. }
  70811. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70812. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70813. if (this.getScene().useRightHandedSystem) {
  70814. this.devicePosition.z *= -1;
  70815. }
  70816. }
  70817. }
  70818. };
  70819. /**
  70820. * WebVR's attach control will start broadcasting frames to the device.
  70821. * Note that in certain browsers (chrome for example) this function must be called
  70822. * within a user-interaction callback. Example:
  70823. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70824. *
  70825. * @param {HTMLElement} element
  70826. * @param {boolean} [noPreventDefault]
  70827. *
  70828. * @memberOf WebVRFreeCamera
  70829. */
  70830. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70831. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70832. this._attached = true;
  70833. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70834. if (this._vrDevice) {
  70835. this.getEngine().enableVR();
  70836. }
  70837. };
  70838. WebVRFreeCamera.prototype.detachControl = function (element) {
  70839. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70840. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70841. _super.prototype.detachControl.call(this, element);
  70842. this._attached = false;
  70843. this.getEngine().disableVR();
  70844. };
  70845. WebVRFreeCamera.prototype.getClassName = function () {
  70846. return "WebVRFreeCamera";
  70847. };
  70848. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70849. //uses the vrDisplay's "resetPose()".
  70850. //pitch and roll won't be affected.
  70851. this._vrDevice.resetPose();
  70852. };
  70853. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70854. var camLeft = this._rigCameras[0];
  70855. var camRight = this._rigCameras[1];
  70856. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70857. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70858. camLeft.position.copyFrom(this.devicePosition);
  70859. camRight.position.copyFrom(this.devicePosition);
  70860. };
  70861. /**
  70862. * This function is called by the two RIG cameras.
  70863. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70864. */
  70865. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70866. var _this = this;
  70867. //WebVR 1.1
  70868. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70869. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70870. if (!this.getScene().useRightHandedSystem) {
  70871. [2, 6, 8, 9, 14].forEach(function (num) {
  70872. _this._webvrViewMatrix.m[num] *= -1;
  70873. });
  70874. }
  70875. // update the camera rotation matrix
  70876. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70877. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70878. // Computing target and final matrix
  70879. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70880. var parentCamera = this._cameraRigParams["parentCamera"];
  70881. // should the view matrix be updated with scale and position offset?
  70882. if (parentCamera.deviceScaleFactor !== 1) {
  70883. this._webvrViewMatrix.invert();
  70884. // scale the position, if set
  70885. if (parentCamera.deviceScaleFactor) {
  70886. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70887. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70888. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70889. }
  70890. this._webvrViewMatrix.invert();
  70891. }
  70892. return this._webvrViewMatrix;
  70893. };
  70894. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70895. var _this = this;
  70896. var parentCamera = this.parent;
  70897. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70898. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70899. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70900. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  70901. //babylon compatible matrix
  70902. if (!this.getScene().useRightHandedSystem) {
  70903. [8, 9, 10, 11].forEach(function (num) {
  70904. _this._projectionMatrix.m[num] *= -1;
  70905. });
  70906. }
  70907. return this._projectionMatrix;
  70908. };
  70909. WebVRFreeCamera.prototype.initControllers = function () {
  70910. var _this = this;
  70911. this.controllers = [];
  70912. var manager = this.getScene().gamepadManager;
  70913. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70914. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70915. var webVrController = gamepad;
  70916. if (webVrController.defaultModel) {
  70917. webVrController.defaultModel.setEnabled(false);
  70918. }
  70919. }
  70920. });
  70921. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70922. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70923. var webVrController_1 = gamepad;
  70924. if (_this.webVROptions.controllerMeshes) {
  70925. if (webVrController_1.defaultModel) {
  70926. webVrController_1.defaultModel.setEnabled(true);
  70927. }
  70928. else {
  70929. // Load the meshes
  70930. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  70931. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  70932. if (_this.webVROptions.defaultLightingOnControllers) {
  70933. if (!_this._lightOnControllers) {
  70934. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  70935. }
  70936. var activateLightOnSubMeshes_1 = function (mesh, light) {
  70937. var children = mesh.getChildren();
  70938. if (children.length !== 0) {
  70939. children.forEach(function (mesh) {
  70940. light.includedOnlyMeshes.push(mesh);
  70941. activateLightOnSubMeshes_1(mesh, light);
  70942. });
  70943. }
  70944. };
  70945. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  70946. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  70947. }
  70948. });
  70949. }
  70950. }
  70951. webVrController_1.attachToPoseControlledCamera(_this);
  70952. // since this is async - sanity check. Is the controller already stored?
  70953. if (_this.controllers.indexOf(webVrController_1) === -1) {
  70954. //add to the controllers array
  70955. _this.controllers.push(webVrController_1);
  70956. //did we find enough controllers? Great! let the developer know.
  70957. if (_this.controllers.length >= 2) {
  70958. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  70959. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  70960. // So we're overriding setting left & right manually to be sure
  70961. var firstViveWandDetected = false;
  70962. for (var i = 0; i < _this.controllers.length; i++) {
  70963. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  70964. if (!firstViveWandDetected) {
  70965. firstViveWandDetected = true;
  70966. _this.controllers[i].hand = "left";
  70967. }
  70968. else {
  70969. _this.controllers[i].hand = "right";
  70970. }
  70971. }
  70972. }
  70973. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  70974. }
  70975. }
  70976. }
  70977. });
  70978. };
  70979. return WebVRFreeCamera;
  70980. }(BABYLON.FreeCamera));
  70981. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  70982. })(BABYLON || (BABYLON = {}));
  70983. //# sourceMappingURL=babylon.webVRCamera.js.map
  70984. var BABYLON;
  70985. (function (BABYLON) {
  70986. // We're mainly based on the logic defined into the FreeCamera code
  70987. var DeviceOrientationCamera = /** @class */ (function (_super) {
  70988. __extends(DeviceOrientationCamera, _super);
  70989. function DeviceOrientationCamera(name, position, scene) {
  70990. var _this = _super.call(this, name, position, scene) || this;
  70991. _this._quaternionCache = new BABYLON.Quaternion();
  70992. _this.inputs.addDeviceOrientation();
  70993. return _this;
  70994. }
  70995. DeviceOrientationCamera.prototype.getClassName = function () {
  70996. return "DeviceOrientationCamera";
  70997. };
  70998. DeviceOrientationCamera.prototype._checkInputs = function () {
  70999. _super.prototype._checkInputs.call(this);
  71000. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71001. if (this._initialQuaternion) {
  71002. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71003. }
  71004. };
  71005. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71006. var _this = this;
  71007. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71008. //can only work if this camera has a rotation quaternion already.
  71009. if (!this.rotationQuaternion)
  71010. return;
  71011. if (!this._initialQuaternion) {
  71012. this._initialQuaternion = new BABYLON.Quaternion();
  71013. }
  71014. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71015. ['x', 'y', 'z'].forEach(function (axisName) {
  71016. if (!axis[axisName]) {
  71017. _this._initialQuaternion[axisName] = 0;
  71018. }
  71019. else {
  71020. _this._initialQuaternion[axisName] *= -1;
  71021. }
  71022. });
  71023. this._initialQuaternion.normalize();
  71024. //force rotation update
  71025. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71026. };
  71027. return DeviceOrientationCamera;
  71028. }(BABYLON.FreeCamera));
  71029. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71030. })(BABYLON || (BABYLON = {}));
  71031. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71032. var BABYLON;
  71033. (function (BABYLON) {
  71034. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71035. __extends(VRDeviceOrientationFreeCamera, _super);
  71036. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71037. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71038. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71039. var _this = _super.call(this, name, position, scene) || this;
  71040. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71041. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71042. return _this;
  71043. }
  71044. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  71045. return "VRDeviceOrientationFreeCamera";
  71046. };
  71047. return VRDeviceOrientationFreeCamera;
  71048. }(BABYLON.DeviceOrientationCamera));
  71049. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  71050. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  71051. __extends(VRDeviceOrientationGamepadCamera, _super);
  71052. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71053. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71054. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71055. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  71056. _this.inputs.addGamepad();
  71057. return _this;
  71058. }
  71059. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  71060. return "VRDeviceOrientationGamepadCamera";
  71061. };
  71062. return VRDeviceOrientationGamepadCamera;
  71063. }(VRDeviceOrientationFreeCamera));
  71064. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  71065. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  71066. __extends(VRDeviceOrientationArcRotateCamera, _super);
  71067. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  71068. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71069. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71070. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71071. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71072. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71073. _this.inputs.addVRDeviceOrientation();
  71074. return _this;
  71075. }
  71076. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  71077. return "VRDeviceOrientationArcRotateCamera";
  71078. };
  71079. return VRDeviceOrientationArcRotateCamera;
  71080. }(BABYLON.ArcRotateCamera));
  71081. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  71082. })(BABYLON || (BABYLON = {}));
  71083. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  71084. var BABYLON;
  71085. (function (BABYLON) {
  71086. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  71087. __extends(AnaglyphFreeCamera, _super);
  71088. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  71089. var _this = _super.call(this, name, position, scene) || this;
  71090. _this.interaxialDistance = interaxialDistance;
  71091. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71092. return _this;
  71093. }
  71094. AnaglyphFreeCamera.prototype.getClassName = function () {
  71095. return "AnaglyphFreeCamera";
  71096. };
  71097. return AnaglyphFreeCamera;
  71098. }(BABYLON.FreeCamera));
  71099. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  71100. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  71101. __extends(AnaglyphArcRotateCamera, _super);
  71102. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  71103. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71104. _this.interaxialDistance = interaxialDistance;
  71105. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71106. return _this;
  71107. }
  71108. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  71109. return "AnaglyphArcRotateCamera";
  71110. };
  71111. return AnaglyphArcRotateCamera;
  71112. }(BABYLON.ArcRotateCamera));
  71113. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  71114. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  71115. __extends(AnaglyphGamepadCamera, _super);
  71116. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  71117. var _this = _super.call(this, name, position, scene) || this;
  71118. _this.interaxialDistance = interaxialDistance;
  71119. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71120. return _this;
  71121. }
  71122. AnaglyphGamepadCamera.prototype.getClassName = function () {
  71123. return "AnaglyphGamepadCamera";
  71124. };
  71125. return AnaglyphGamepadCamera;
  71126. }(BABYLON.GamepadCamera));
  71127. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  71128. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  71129. __extends(AnaglyphUniversalCamera, _super);
  71130. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  71131. var _this = _super.call(this, name, position, scene) || this;
  71132. _this.interaxialDistance = interaxialDistance;
  71133. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71134. return _this;
  71135. }
  71136. AnaglyphUniversalCamera.prototype.getClassName = function () {
  71137. return "AnaglyphUniversalCamera";
  71138. };
  71139. return AnaglyphUniversalCamera;
  71140. }(BABYLON.UniversalCamera));
  71141. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  71142. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  71143. __extends(StereoscopicFreeCamera, _super);
  71144. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71145. var _this = _super.call(this, name, position, scene) || this;
  71146. _this.interaxialDistance = interaxialDistance;
  71147. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71148. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71149. return _this;
  71150. }
  71151. StereoscopicFreeCamera.prototype.getClassName = function () {
  71152. return "StereoscopicFreeCamera";
  71153. };
  71154. return StereoscopicFreeCamera;
  71155. }(BABYLON.FreeCamera));
  71156. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  71157. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  71158. __extends(StereoscopicArcRotateCamera, _super);
  71159. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  71160. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71161. _this.interaxialDistance = interaxialDistance;
  71162. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71163. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71164. return _this;
  71165. }
  71166. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  71167. return "StereoscopicArcRotateCamera";
  71168. };
  71169. return StereoscopicArcRotateCamera;
  71170. }(BABYLON.ArcRotateCamera));
  71171. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  71172. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  71173. __extends(StereoscopicGamepadCamera, _super);
  71174. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71175. var _this = _super.call(this, name, position, scene) || this;
  71176. _this.interaxialDistance = interaxialDistance;
  71177. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71178. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71179. return _this;
  71180. }
  71181. StereoscopicGamepadCamera.prototype.getClassName = function () {
  71182. return "StereoscopicGamepadCamera";
  71183. };
  71184. return StereoscopicGamepadCamera;
  71185. }(BABYLON.GamepadCamera));
  71186. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  71187. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  71188. __extends(StereoscopicUniversalCamera, _super);
  71189. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71190. var _this = _super.call(this, name, position, scene) || this;
  71191. _this.interaxialDistance = interaxialDistance;
  71192. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71193. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71194. return _this;
  71195. }
  71196. StereoscopicUniversalCamera.prototype.getClassName = function () {
  71197. return "StereoscopicUniversalCamera";
  71198. };
  71199. return StereoscopicUniversalCamera;
  71200. }(BABYLON.UniversalCamera));
  71201. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  71202. })(BABYLON || (BABYLON = {}));
  71203. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  71204. var BABYLON;
  71205. (function (BABYLON) {
  71206. var VRExperienceHelper = /** @class */ (function () {
  71207. function VRExperienceHelper(scene, webVROptions) {
  71208. if (webVROptions === void 0) { webVROptions = {}; }
  71209. var _this = this;
  71210. this.webVROptions = webVROptions;
  71211. // Can the system support WebVR, even if a headset isn't plugged in?
  71212. this._webVRsupported = false;
  71213. // If WebVR is supported, is a headset plugged in and are we ready to present?
  71214. this._webVRready = false;
  71215. // Are we waiting for the requestPresent callback to complete?
  71216. this._webVRrequesting = false;
  71217. // Are we presenting to the headset right now?
  71218. this._webVRpresenting = false;
  71219. // Are we presenting in the fullscreen fallback?
  71220. this._fullscreenVRpresenting = false;
  71221. this.onEnteringVR = new BABYLON.Observable();
  71222. this.onExitingVR = new BABYLON.Observable();
  71223. this.onControllerMeshLoaded = new BABYLON.Observable();
  71224. this._useCustomVRButton = false;
  71225. this._teleportationRequested = false;
  71226. this._teleportationEnabledOnLeftController = false;
  71227. this._teleportationEnabledOnRightController = false;
  71228. this._leftControllerReady = false;
  71229. this._rightControllerReady = false;
  71230. this._teleportationAllowed = false;
  71231. this._rotationAllowed = true;
  71232. this._teleportationRequestInitiated = false;
  71233. this._rotationRightAsked = false;
  71234. this._rotationLeftAsked = false;
  71235. this._teleportationFillColor = "#444444";
  71236. this._teleportationBorderColor = "#FFFFFF";
  71237. this._rotationAngle = 0;
  71238. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  71239. this._padSensibilityUp = 0.65;
  71240. this._padSensibilityDown = 0.35;
  71241. this.onNewMeshSelected = new BABYLON.Observable();
  71242. this._pointerDownOnMeshAsked = false;
  71243. this._isActionableMesh = false;
  71244. this._workingVector = BABYLON.Vector3.Zero();
  71245. this._scene = scene;
  71246. this._defaultHeight = webVROptions.defaultHeight || 1.7;
  71247. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  71248. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  71249. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  71250. }
  71251. else {
  71252. this._position = this._scene.activeCamera.position.clone();
  71253. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  71254. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  71255. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  71256. // Set rotation from previous camera
  71257. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  71258. var targetCamera = this._scene.activeCamera;
  71259. if (targetCamera.rotationQuaternion) {
  71260. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  71261. }
  71262. else {
  71263. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  71264. }
  71265. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  71266. }
  71267. }
  71268. this._scene.activeCamera = this._deviceOrientationCamera;
  71269. this._canvas = scene.getEngine().getRenderingCanvas();
  71270. if (this._canvas) {
  71271. this._scene.activeCamera.attachControl(this._canvas);
  71272. }
  71273. if (webVROptions) {
  71274. if (webVROptions.useCustomVRButton) {
  71275. this._useCustomVRButton = true;
  71276. if (webVROptions.customVRButton) {
  71277. this._btnVR = webVROptions.customVRButton;
  71278. }
  71279. }
  71280. if (webVROptions.rayLength) {
  71281. this._rayLength = webVROptions.rayLength;
  71282. }
  71283. }
  71284. if (!this._useCustomVRButton) {
  71285. this._btnVR = document.createElement("BUTTON");
  71286. this._btnVR.className = "babylonVRicon";
  71287. this._btnVR.id = "babylonVRiconbtn";
  71288. this._btnVR.title = "Click to switch to VR";
  71289. 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) }";
  71290. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  71291. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  71292. // css += ".babylonVRicon.vrdisplaysupported { }";
  71293. // css += ".babylonVRicon.vrdisplayready { }";
  71294. // css += ".babylonVRicon.vrdisplayrequesting { }";
  71295. var style = document.createElement('style');
  71296. style.appendChild(document.createTextNode(css));
  71297. document.getElementsByTagName('head')[0].appendChild(style);
  71298. }
  71299. if (this._canvas) {
  71300. if (!this._useCustomVRButton) {
  71301. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71302. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71303. }
  71304. if (this._btnVR) {
  71305. this._btnVR.addEventListener("click", function () {
  71306. _this.enterVR();
  71307. });
  71308. }
  71309. window.addEventListener("resize", function () {
  71310. if (_this._canvas && !_this._useCustomVRButton) {
  71311. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  71312. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  71313. }
  71314. if (_this._fullscreenVRpresenting && _this._webVRready) {
  71315. _this.exitVR();
  71316. }
  71317. });
  71318. }
  71319. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71320. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71321. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71322. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71323. if (!this._useCustomVRButton) {
  71324. document.body.appendChild(this._btnVR);
  71325. }
  71326. // Exiting VR mode using 'ESC' key on desktop
  71327. this._onKeyDown = function (event) {
  71328. if (event.keyCode === 27 && _this.isInVRMode()) {
  71329. _this.exitVR();
  71330. }
  71331. };
  71332. document.addEventListener("keydown", this._onKeyDown);
  71333. // Exiting VR mode double tapping the touch screen
  71334. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  71335. if (_this.isInVRMode()) {
  71336. _this.exitVR();
  71337. if (_this._fullscreenVRpresenting) {
  71338. _this._scene.getEngine().switchFullscreen(true);
  71339. }
  71340. }
  71341. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  71342. // Listen for WebVR display changes
  71343. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  71344. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  71345. this._onVRRequestPresentStart = function () {
  71346. _this._webVRrequesting = true;
  71347. _this.updateButtonVisibility();
  71348. };
  71349. this._onVRRequestPresentComplete = function (success) {
  71350. _this._webVRrequesting = false;
  71351. _this.updateButtonVisibility();
  71352. };
  71353. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  71354. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  71355. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  71356. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71357. // Create the cameras
  71358. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  71359. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  71360. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  71361. this.updateButtonVisibility();
  71362. //create easing functions
  71363. this._circleEase = new BABYLON.CircleEase();
  71364. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71365. }
  71366. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  71367. get: function () {
  71368. return this._deviceOrientationCamera;
  71369. },
  71370. enumerable: true,
  71371. configurable: true
  71372. });
  71373. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  71374. // Based on the current WebVR support, returns the current VR camera used
  71375. get: function () {
  71376. if (this._webVRready) {
  71377. return this._webVRCamera;
  71378. }
  71379. else {
  71380. return this._vrDeviceOrientationCamera;
  71381. }
  71382. },
  71383. enumerable: true,
  71384. configurable: true
  71385. });
  71386. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  71387. get: function () {
  71388. return this._webVRCamera;
  71389. },
  71390. enumerable: true,
  71391. configurable: true
  71392. });
  71393. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  71394. get: function () {
  71395. return this._vrDeviceOrientationCamera;
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. // Raised when one of the controller has loaded successfully its associated default mesh
  71401. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  71402. if (webVRController.hand === "left") {
  71403. this._leftControllerReady = true;
  71404. if (this._teleportationRequested && !this._teleportationEnabledOnLeftController) {
  71405. this._enableTeleportationOnController(webVRController);
  71406. }
  71407. }
  71408. if (webVRController.hand === "right") {
  71409. this._rightControllerReady = true;
  71410. if (this._teleportationRequested && !this._teleportationEnabledOnRightController) {
  71411. this._enableTeleportationOnController(webVRController);
  71412. }
  71413. }
  71414. if (this.onControllerMeshLoaded) {
  71415. this.onControllerMeshLoaded.notifyObservers(webVRController);
  71416. }
  71417. };
  71418. VRExperienceHelper.prototype._onFullscreenChange = function () {
  71419. if (document.fullscreen !== undefined) {
  71420. this._fullscreenVRpresenting = document.fullscreen;
  71421. }
  71422. else if (document.mozFullScreen !== undefined) {
  71423. this._fullscreenVRpresenting = document.mozFullScreen;
  71424. }
  71425. else if (document.webkitIsFullScreen !== undefined) {
  71426. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71427. }
  71428. else if (document.msIsFullScreen !== undefined) {
  71429. this._fullscreenVRpresenting = document.msIsFullScreen;
  71430. }
  71431. if (!this._fullscreenVRpresenting && this._canvas) {
  71432. this.exitVR();
  71433. if (!this._useCustomVRButton) {
  71434. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71435. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71436. }
  71437. }
  71438. };
  71439. VRExperienceHelper.prototype.isInVRMode = function () {
  71440. return this._webVRpresenting || this._fullscreenVRpresenting;
  71441. };
  71442. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  71443. var vrDisplay = this._scene.getEngine().getVRDevice();
  71444. if (vrDisplay) {
  71445. var wasPresenting = this._webVRpresenting;
  71446. // A VR display is connected
  71447. this._webVRpresenting = vrDisplay.isPresenting;
  71448. if (wasPresenting && !this._webVRpresenting)
  71449. this.exitVR();
  71450. }
  71451. else {
  71452. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  71453. }
  71454. this.updateButtonVisibility();
  71455. };
  71456. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  71457. this._webVRsupported = eventArgs.vrSupported;
  71458. this._webVRready = !!eventArgs.vrDisplay;
  71459. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  71460. this.updateButtonVisibility();
  71461. };
  71462. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  71463. if (!this._btnVR) {
  71464. return;
  71465. }
  71466. this._btnVR.className = "babylonVRicon";
  71467. if (this.isInVRMode()) {
  71468. this._btnVR.className += " vrdisplaypresenting";
  71469. }
  71470. else {
  71471. if (this._webVRready)
  71472. this._btnVR.className += " vrdisplayready";
  71473. if (this._webVRsupported)
  71474. this._btnVR.className += " vrdisplaysupported";
  71475. if (this._webVRrequesting)
  71476. this._btnVR.className += " vrdisplayrequesting";
  71477. }
  71478. };
  71479. /**
  71480. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  71481. * Otherwise, will use the fullscreen API.
  71482. */
  71483. VRExperienceHelper.prototype.enterVR = function () {
  71484. if (this._scene.activeCamera) {
  71485. this._position = this._scene.activeCamera.position.clone();
  71486. }
  71487. if (this.onEnteringVR) {
  71488. this.onEnteringVR.notifyObservers({});
  71489. }
  71490. if (this._webVRrequesting)
  71491. return;
  71492. // If WebVR is supported and a headset is connected
  71493. if (this._webVRready) {
  71494. if (!this._webVRpresenting) {
  71495. this._webVRCamera.position = this._position;
  71496. this._scene.activeCamera = this._webVRCamera;
  71497. }
  71498. }
  71499. else {
  71500. this._vrDeviceOrientationCamera.position = this._position;
  71501. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  71502. this._scene.getEngine().switchFullscreen(true);
  71503. this.updateButtonVisibility();
  71504. }
  71505. if (this._scene.activeCamera && this._canvas) {
  71506. this._scene.activeCamera.attachControl(this._canvas);
  71507. }
  71508. };
  71509. /**
  71510. * Attempt to exit VR, or fullscreen.
  71511. */
  71512. VRExperienceHelper.prototype.exitVR = function () {
  71513. if (this.onExitingVR) {
  71514. this.onExitingVR.notifyObservers({});
  71515. }
  71516. if (this._webVRpresenting) {
  71517. this._scene.getEngine().disableVR();
  71518. }
  71519. if (this._scene.activeCamera) {
  71520. this._position = this._scene.activeCamera.position.clone();
  71521. }
  71522. this._deviceOrientationCamera.position = this._position;
  71523. this._scene.activeCamera = this._deviceOrientationCamera;
  71524. if (this._canvas) {
  71525. this._scene.activeCamera.attachControl(this._canvas);
  71526. }
  71527. this.updateButtonVisibility();
  71528. };
  71529. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  71530. get: function () {
  71531. return this._position;
  71532. },
  71533. set: function (value) {
  71534. this._position = value;
  71535. if (this._scene.activeCamera) {
  71536. this._scene.activeCamera.position = value;
  71537. }
  71538. },
  71539. enumerable: true,
  71540. configurable: true
  71541. });
  71542. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  71543. var _this = this;
  71544. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  71545. this._teleportationRequested = true;
  71546. if (vrTeleportationOptions) {
  71547. if (vrTeleportationOptions.floorMeshName) {
  71548. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  71549. }
  71550. }
  71551. if (this._leftControllerReady && this._webVRCamera.leftController) {
  71552. this._enableTeleportationOnController(this._webVRCamera.leftController);
  71553. }
  71554. if (this._rightControllerReady && this._webVRCamera.rightController) {
  71555. this._enableTeleportationOnController(this._webVRCamera.rightController);
  71556. }
  71557. this._scene.gamepadManager.onGamepadConnectedObservable.add(function (pad) { return _this._onNewGamepadConnected(pad); });
  71558. // Creates an image processing post process for the vignette not relying
  71559. // on the main scene configuration for image processing to reduce setup and spaces
  71560. // (gamma/linear) conflicts.
  71561. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  71562. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  71563. imageProcessingConfiguration.vignetteEnabled = true;
  71564. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  71565. this._webVRCamera.detachPostProcess(this._postProcessMove);
  71566. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  71567. this._createGazeTracker();
  71568. this._createTeleportationCircles();
  71569. this.raySelectionPredicate = function (mesh) {
  71570. return true;
  71571. };
  71572. this.meshSelectionPredicate = function (mesh) {
  71573. return true;
  71574. };
  71575. this._raySelectionPredicate = function (mesh) {
  71576. if (mesh.name.indexOf(_this._floorMeshName) !== -1 || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  71577. && mesh.name.indexOf("teleportationCircle") === -1
  71578. && mesh.name.indexOf("torusTeleportation") === -1
  71579. && mesh.name.indexOf("laserPointer") === -1)) {
  71580. return _this.raySelectionPredicate(mesh);
  71581. }
  71582. return false;
  71583. };
  71584. this._scene.registerBeforeRender(function () {
  71585. _this._castRayAndSelectObject();
  71586. });
  71587. };
  71588. VRExperienceHelper.prototype._onNewGamepadConnected = function (gamepad) {
  71589. var _this = this;
  71590. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71591. if (gamepad.leftStick) {
  71592. gamepad.onleftstickchanged(function (stickValues) {
  71593. // Listening to classic/xbox gamepad only if no VR controller is active
  71594. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  71595. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  71596. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  71597. if (!_this._teleportationRequestInitiated) {
  71598. if (stickValues.y < -_this._padSensibilityUp) {
  71599. _this._teleportationRequestInitiated = true;
  71600. }
  71601. }
  71602. else {
  71603. if (stickValues.y > -_this._padSensibilityDown) {
  71604. if (_this._teleportationAllowed) {
  71605. _this._teleportCamera();
  71606. }
  71607. _this._teleportationRequestInitiated = false;
  71608. }
  71609. }
  71610. }
  71611. });
  71612. }
  71613. if (gamepad.rightStick) {
  71614. gamepad.onrightstickchanged(function (stickValues) {
  71615. if (!_this._rotationLeftAsked) {
  71616. if (stickValues.x < -_this._padSensibilityUp) {
  71617. _this._rotationLeftAsked = true;
  71618. if (_this._rotationAllowed) {
  71619. _this._rotateCamera(false);
  71620. }
  71621. }
  71622. }
  71623. else {
  71624. if (stickValues.x > -_this._padSensibilityDown) {
  71625. _this._rotationLeftAsked = false;
  71626. }
  71627. }
  71628. if (!_this._rotationRightAsked) {
  71629. if (stickValues.x > _this._padSensibilityUp) {
  71630. _this._rotationRightAsked = true;
  71631. if (_this._rotationAllowed) {
  71632. _this._rotateCamera(true);
  71633. }
  71634. }
  71635. }
  71636. else {
  71637. if (stickValues.x < _this._padSensibilityDown) {
  71638. _this._rotationRightAsked = false;
  71639. }
  71640. }
  71641. });
  71642. }
  71643. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  71644. gamepad.onbuttondown(function (buttonPressed) {
  71645. if (buttonPressed === BABYLON.Xbox360Button.A) {
  71646. _this._pointerDownOnMeshAsked = true;
  71647. if (_this._currentMeshSelected && _this._currentHit) {
  71648. _this._scene.simulatePointerDown(_this._currentHit);
  71649. }
  71650. }
  71651. });
  71652. gamepad.onbuttonup(function (buttonPressed) {
  71653. if (buttonPressed === BABYLON.Xbox360Button.A) {
  71654. if (_this._currentMeshSelected && _this._currentHit) {
  71655. _this._scene.simulatePointerUp(_this._currentHit);
  71656. }
  71657. _this._pointerDownOnMeshAsked = false;
  71658. }
  71659. });
  71660. }
  71661. }
  71662. };
  71663. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  71664. var _this = this;
  71665. var controllerMesh = webVRController.mesh;
  71666. if (controllerMesh) {
  71667. var childMeshes = controllerMesh.getChildMeshes();
  71668. for (var i = 0; i < childMeshes.length; i++) {
  71669. if (childMeshes[i].name === "POINTING_POSE") {
  71670. controllerMesh = childMeshes[i];
  71671. break;
  71672. }
  71673. }
  71674. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  71675. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  71676. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71677. laserPointerMaterial.alpha = 0.6;
  71678. laserPointer.material = laserPointerMaterial;
  71679. laserPointer.rotation.x = Math.PI / 2;
  71680. laserPointer.parent = controllerMesh;
  71681. laserPointer.position.z = -0.5;
  71682. laserPointer.position.y = 0;
  71683. laserPointer.isVisible = false;
  71684. if (webVRController.hand === "left") {
  71685. this._leftLaserPointer = laserPointer;
  71686. }
  71687. else {
  71688. this._rightLaserPointer = laserPointer;
  71689. }
  71690. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  71691. // Enabling / disabling laserPointer
  71692. if (stateObject.value === 1) {
  71693. laserPointer.isVisible = !laserPointer.isVisible;
  71694. // Laser pointer can only be active on left or right, not both at the same time
  71695. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  71696. _this._rightLaserPointer.isVisible = false;
  71697. }
  71698. else if (_this._leftLaserPointer) {
  71699. _this._leftLaserPointer.isVisible = false;
  71700. }
  71701. }
  71702. });
  71703. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  71704. if (!_this._teleportationRequestInitiated) {
  71705. if (stateObject.y < -_this._padSensibilityUp) {
  71706. // If laser pointer wasn't enabled yet
  71707. if (webVRController.hand === "left" && _this._leftLaserPointer) {
  71708. _this._leftLaserPointer.isVisible = true;
  71709. if (_this._rightLaserPointer) {
  71710. _this._rightLaserPointer.isVisible = false;
  71711. }
  71712. }
  71713. else if (_this._rightLaserPointer) {
  71714. _this._rightLaserPointer.isVisible = true;
  71715. if (_this._leftLaserPointer) {
  71716. _this._leftLaserPointer.isVisible = false;
  71717. }
  71718. }
  71719. _this._teleportationRequestInitiated = true;
  71720. }
  71721. }
  71722. else {
  71723. // Listening to the proper controller values changes to confirm teleportation
  71724. if ((webVRController.hand === "left" && _this._leftLaserPointer && _this._leftLaserPointer.isVisible)
  71725. || (webVRController.hand === "right" && _this._rightLaserPointer && _this._rightLaserPointer.isVisible)) {
  71726. if (stateObject.y > -_this._padSensibilityDown) {
  71727. if (_this._teleportationAllowed) {
  71728. _this._teleportationAllowed = false;
  71729. _this._teleportCamera();
  71730. }
  71731. _this._teleportationRequestInitiated = false;
  71732. }
  71733. }
  71734. }
  71735. if (!_this._rotationLeftAsked) {
  71736. if (stateObject.x < -_this._padSensibilityUp) {
  71737. _this._rotationLeftAsked = true;
  71738. if (_this._rotationAllowed) {
  71739. _this._rotateCamera(false);
  71740. }
  71741. }
  71742. }
  71743. else {
  71744. if (stateObject.x > -_this._padSensibilityDown) {
  71745. _this._rotationLeftAsked = false;
  71746. }
  71747. }
  71748. if (!_this._rotationRightAsked) {
  71749. if (stateObject.x > _this._padSensibilityUp) {
  71750. _this._rotationRightAsked = true;
  71751. if (_this._rotationAllowed) {
  71752. _this._rotateCamera(true);
  71753. }
  71754. }
  71755. }
  71756. else {
  71757. if (stateObject.x < _this._padSensibilityDown) {
  71758. _this._rotationRightAsked = false;
  71759. }
  71760. }
  71761. });
  71762. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  71763. if (!_this._pointerDownOnMeshAsked) {
  71764. if (stateObject.value > _this._padSensibilityUp) {
  71765. _this._pointerDownOnMeshAsked = true;
  71766. if (_this._currentMeshSelected && _this._currentHit) {
  71767. _this._scene.simulatePointerDown(_this._currentHit);
  71768. }
  71769. }
  71770. }
  71771. else if (stateObject.value < _this._padSensibilityDown) {
  71772. if (_this._currentMeshSelected && _this._currentHit) {
  71773. _this._scene.simulatePointerUp(_this._currentHit);
  71774. }
  71775. _this._pointerDownOnMeshAsked = false;
  71776. }
  71777. });
  71778. }
  71779. };
  71780. // Gaze support used to point to teleport or to interact with an object
  71781. VRExperienceHelper.prototype._createGazeTracker = function () {
  71782. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  71783. this._gazeTracker.bakeCurrentTransformIntoVertices();
  71784. this._gazeTracker.isPickable = false;
  71785. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  71786. targetMat.specularColor = BABYLON.Color3.Black();
  71787. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71788. targetMat.backFaceCulling = false;
  71789. this._gazeTracker.material = targetMat;
  71790. };
  71791. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  71792. this._teleportationCircle = BABYLON.Mesh.CreateGround("teleportationCircle", 2, 2, 2, this._scene);
  71793. this._teleportationCircle.isPickable = false;
  71794. var length = 512;
  71795. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  71796. dynamicTexture.hasAlpha = true;
  71797. var context = dynamicTexture.getContext();
  71798. var centerX = length / 2;
  71799. var centerY = length / 2;
  71800. var radius = 200;
  71801. context.beginPath();
  71802. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  71803. context.fillStyle = this._teleportationFillColor;
  71804. context.fill();
  71805. context.lineWidth = 10;
  71806. context.strokeStyle = this._teleportationBorderColor;
  71807. context.stroke();
  71808. context.closePath();
  71809. dynamicTexture.update();
  71810. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  71811. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  71812. this._teleportationCircle.material = teleportationCircleMaterial;
  71813. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  71814. torus.isPickable = false;
  71815. torus.parent = this._teleportationCircle;
  71816. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  71817. var keys = [];
  71818. keys.push({
  71819. frame: 0,
  71820. value: 0
  71821. });
  71822. keys.push({
  71823. frame: 30,
  71824. value: 0.4
  71825. });
  71826. keys.push({
  71827. frame: 60,
  71828. value: 0
  71829. });
  71830. animationInnerCircle.setKeys(keys);
  71831. var easingFunction = new BABYLON.SineEase();
  71832. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71833. animationInnerCircle.setEasingFunction(easingFunction);
  71834. torus.animations = [];
  71835. torus.animations.push(animationInnerCircle);
  71836. this._scene.beginAnimation(torus, 0, 60, true);
  71837. this._hideTeleportationCircle();
  71838. };
  71839. VRExperienceHelper.prototype._displayTeleportationCircle = function () {
  71840. this._teleportationCircle.isVisible = true;
  71841. this._teleportationCircle.getChildren()[0].isVisible = true;
  71842. };
  71843. VRExperienceHelper.prototype._hideTeleportationCircle = function () {
  71844. this._teleportationCircle.isVisible = false;
  71845. this._teleportationCircle.getChildren()[0].isVisible = false;
  71846. };
  71847. VRExperienceHelper.prototype._rotateCamera = function (right) {
  71848. var _this = this;
  71849. if (right) {
  71850. this._rotationAngle++;
  71851. }
  71852. else {
  71853. this._rotationAngle--;
  71854. }
  71855. this.currentVRCamera.animations = [];
  71856. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  71857. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71858. var animationRotationKeys = [];
  71859. animationRotationKeys.push({
  71860. frame: 0,
  71861. value: this.currentVRCamera.rotationQuaternion
  71862. });
  71863. animationRotationKeys.push({
  71864. frame: 6,
  71865. value: target
  71866. });
  71867. animationRotation.setKeys(animationRotationKeys);
  71868. animationRotation.setEasingFunction(this._circleEase);
  71869. this.currentVRCamera.animations.push(animationRotation);
  71870. this._postProcessMove.animations = [];
  71871. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71872. var vignetteWeightKeys = [];
  71873. vignetteWeightKeys.push({
  71874. frame: 0,
  71875. value: 0
  71876. });
  71877. vignetteWeightKeys.push({
  71878. frame: 3,
  71879. value: 4
  71880. });
  71881. vignetteWeightKeys.push({
  71882. frame: 6,
  71883. value: 0
  71884. });
  71885. animationPP.setKeys(vignetteWeightKeys);
  71886. animationPP.setEasingFunction(this._circleEase);
  71887. this._postProcessMove.animations.push(animationPP);
  71888. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71889. var vignetteStretchKeys = [];
  71890. vignetteStretchKeys.push({
  71891. frame: 0,
  71892. value: 0
  71893. });
  71894. vignetteStretchKeys.push({
  71895. frame: 3,
  71896. value: 10
  71897. });
  71898. vignetteStretchKeys.push({
  71899. frame: 6,
  71900. value: 0
  71901. });
  71902. animationPP2.setKeys(vignetteStretchKeys);
  71903. animationPP2.setEasingFunction(this._circleEase);
  71904. this._postProcessMove.animations.push(animationPP2);
  71905. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  71906. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  71907. this._webVRCamera.attachPostProcess(this._postProcessMove);
  71908. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  71909. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  71910. });
  71911. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  71912. };
  71913. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  71914. if (hit.pickedPoint) {
  71915. this._teleportationAllowed = true;
  71916. if (this._teleportationRequestInitiated) {
  71917. this._displayTeleportationCircle();
  71918. }
  71919. else {
  71920. this._hideTeleportationCircle();
  71921. }
  71922. this._haloCenter.copyFrom(hit.pickedPoint);
  71923. this._teleportationCircle.position.copyFrom(hit.pickedPoint);
  71924. var pickNormal = hit.getNormal();
  71925. if (pickNormal) {
  71926. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  71927. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  71928. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationCircle.rotation);
  71929. }
  71930. this._teleportationCircle.position.y += 0.1;
  71931. }
  71932. };
  71933. VRExperienceHelper.prototype._teleportCamera = function () {
  71934. var _this = this;
  71935. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  71936. // offset of the headset from the anchor. Then add the helper's position to account for user's height offset
  71937. this.webVRCamera.leftCamera.globalPosition.subtractToRef(this.webVRCamera.position, this._workingVector);
  71938. this._haloCenter.subtractToRef(this._workingVector, this._workingVector);
  71939. this._workingVector.y += this._defaultHeight;
  71940. // Create animation from the camera's position to the new location
  71941. this.currentVRCamera.animations = [];
  71942. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71943. var animationCameraTeleportationKeys = [{
  71944. frame: 0,
  71945. value: this.currentVRCamera.position
  71946. },
  71947. {
  71948. frame: 11,
  71949. value: this._workingVector
  71950. }
  71951. ];
  71952. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  71953. animationCameraTeleportation.setEasingFunction(this._circleEase);
  71954. this.currentVRCamera.animations.push(animationCameraTeleportation);
  71955. this._postProcessMove.animations = [];
  71956. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71957. var vignetteWeightKeys = [];
  71958. vignetteWeightKeys.push({
  71959. frame: 0,
  71960. value: 0
  71961. });
  71962. vignetteWeightKeys.push({
  71963. frame: 5,
  71964. value: 8
  71965. });
  71966. vignetteWeightKeys.push({
  71967. frame: 11,
  71968. value: 0
  71969. });
  71970. animationPP.setKeys(vignetteWeightKeys);
  71971. this._postProcessMove.animations.push(animationPP);
  71972. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71973. var vignetteStretchKeys = [];
  71974. vignetteStretchKeys.push({
  71975. frame: 0,
  71976. value: 0
  71977. });
  71978. vignetteStretchKeys.push({
  71979. frame: 5,
  71980. value: 10
  71981. });
  71982. vignetteStretchKeys.push({
  71983. frame: 11,
  71984. value: 0
  71985. });
  71986. animationPP2.setKeys(vignetteStretchKeys);
  71987. this._postProcessMove.animations.push(animationPP2);
  71988. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 8;
  71989. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 10;
  71990. this._webVRCamera.attachPostProcess(this._postProcessMove);
  71991. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  71992. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  71993. });
  71994. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  71995. };
  71996. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  71997. var ray;
  71998. if ((!this.currentVRCamera.rightController && !this.currentVRCamera.leftController) ||
  71999. (this._leftLaserPointer && !this._leftLaserPointer.isVisible && !this._rightLaserPointer) ||
  72000. (this._rightLaserPointer && !this._rightLaserPointer.isVisible && !this._leftLaserPointer) ||
  72001. (this._rightLaserPointer && this._leftLaserPointer && !this._rightLaserPointer.isVisible && !this._leftLaserPointer.isVisible)) {
  72002. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  72003. }
  72004. else {
  72005. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72006. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  72007. }
  72008. else {
  72009. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  72010. }
  72011. }
  72012. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  72013. // Moving the gazeTracker on the mesh face targetted
  72014. if (hit && hit.pickedPoint) {
  72015. this._gazeTracker.isVisible = true;
  72016. var multiplier = 1;
  72017. if (this._isActionableMesh) {
  72018. multiplier = 3;
  72019. }
  72020. this._gazeTracker.scaling.x = hit.distance * multiplier;
  72021. this._gazeTracker.scaling.y = hit.distance * multiplier;
  72022. this._gazeTracker.scaling.z = hit.distance * multiplier;
  72023. var pickNormal = hit.getNormal();
  72024. // To avoid z-fighting
  72025. var deltaFighting = 0.002;
  72026. if (pickNormal) {
  72027. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72028. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72029. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  72030. }
  72031. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  72032. if (this._gazeTracker.position.x < 0) {
  72033. this._gazeTracker.position.x += deltaFighting;
  72034. }
  72035. else {
  72036. this._gazeTracker.position.x -= deltaFighting;
  72037. }
  72038. if (this._gazeTracker.position.y < 0) {
  72039. this._gazeTracker.position.y += deltaFighting;
  72040. }
  72041. else {
  72042. this._gazeTracker.position.y -= deltaFighting;
  72043. }
  72044. if (this._gazeTracker.position.z < 0) {
  72045. this._gazeTracker.position.z += deltaFighting;
  72046. }
  72047. else {
  72048. this._gazeTracker.position.z -= deltaFighting;
  72049. }
  72050. // Changing the size of the laser pointer based on the distance from the targetted point
  72051. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  72052. this._rightLaserPointer.scaling.y = hit.distance;
  72053. this._rightLaserPointer.position.z = -hit.distance / 2;
  72054. }
  72055. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72056. this._leftLaserPointer.scaling.y = hit.distance;
  72057. this._leftLaserPointer.position.z = -hit.distance / 2;
  72058. }
  72059. }
  72060. else {
  72061. this._gazeTracker.isVisible = false;
  72062. }
  72063. if (hit && hit.pickedMesh) {
  72064. this._currentHit = hit;
  72065. if (this._pointerDownOnMeshAsked) {
  72066. this._scene.simulatePointerMove(this._currentHit);
  72067. }
  72068. // The object selected is the floor, we're in a teleportation scenario
  72069. if (hit.pickedMesh.name.indexOf(this._floorMeshName) !== -1 && hit.pickedPoint) {
  72070. // Moving the teleportation area to this targetted point
  72071. this._moveTeleportationSelectorTo(hit);
  72072. return;
  72073. }
  72074. // If not, we're in a selection scenario
  72075. this._hideTeleportationCircle();
  72076. this._teleportationAllowed = false;
  72077. if (hit.pickedMesh !== this._currentMeshSelected) {
  72078. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  72079. this._currentMeshSelected = hit.pickedMesh;
  72080. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  72081. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  72082. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  72083. this._isActionableMesh = true;
  72084. }
  72085. else {
  72086. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72087. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72088. this._isActionableMesh = false;
  72089. }
  72090. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  72091. }
  72092. else {
  72093. this._currentMeshSelected = null;
  72094. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72095. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72096. }
  72097. }
  72098. }
  72099. else {
  72100. this._currentHit = null;
  72101. this._currentMeshSelected = null;
  72102. this._teleportationAllowed = false;
  72103. this._hideTeleportationCircle();
  72104. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72105. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72106. }
  72107. };
  72108. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  72109. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  72110. this._leftLaserPointer.material.emissiveColor = color;
  72111. }
  72112. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  72113. this._rightLaserPointer.material.emissiveColor = color;
  72114. }
  72115. };
  72116. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  72117. if (this._gazeTracker.material) {
  72118. this._gazeTracker.material.emissiveColor = color;
  72119. }
  72120. };
  72121. VRExperienceHelper.prototype.dispose = function () {
  72122. if (this.isInVRMode()) {
  72123. this.exitVR();
  72124. }
  72125. this._deviceOrientationCamera.dispose();
  72126. if (this._passProcessMove) {
  72127. this._passProcessMove.dispose();
  72128. }
  72129. if (this._postProcessMove) {
  72130. this._postProcessMove.dispose();
  72131. }
  72132. if (this._webVRCamera) {
  72133. this._webVRCamera.dispose();
  72134. }
  72135. if (this._vrDeviceOrientationCamera) {
  72136. this._vrDeviceOrientationCamera.dispose();
  72137. }
  72138. if (!this._useCustomVRButton) {
  72139. document.body.removeChild(this._btnVR);
  72140. }
  72141. document.removeEventListener("keydown", this._onKeyDown);
  72142. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72143. };
  72144. VRExperienceHelper.prototype.getClassName = function () {
  72145. return "VRExperienceHelper";
  72146. };
  72147. return VRExperienceHelper;
  72148. }());
  72149. BABYLON.VRExperienceHelper = VRExperienceHelper;
  72150. })(BABYLON || (BABYLON = {}));
  72151. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  72152. // Mainly based on these 2 articles :
  72153. // 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
  72154. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  72155. var BABYLON;
  72156. (function (BABYLON) {
  72157. var JoystickAxis;
  72158. (function (JoystickAxis) {
  72159. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  72160. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  72161. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  72162. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  72163. var VirtualJoystick = /** @class */ (function () {
  72164. function VirtualJoystick(leftJoystick) {
  72165. var _this = this;
  72166. if (leftJoystick) {
  72167. this._leftJoystick = true;
  72168. }
  72169. else {
  72170. this._leftJoystick = false;
  72171. }
  72172. VirtualJoystick._globalJoystickIndex++;
  72173. // By default left & right arrow keys are moving the X
  72174. // and up & down keys are moving the Y
  72175. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72176. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72177. this.reverseLeftRight = false;
  72178. this.reverseUpDown = false;
  72179. // collections of pointers
  72180. this._touches = new BABYLON.StringDictionary();
  72181. this.deltaPosition = BABYLON.Vector3.Zero();
  72182. this._joystickSensibility = 25;
  72183. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72184. this._onResize = function (evt) {
  72185. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72186. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72187. if (VirtualJoystick.vjCanvas) {
  72188. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  72189. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  72190. }
  72191. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  72192. };
  72193. // injecting a canvas element on top of the canvas 3D game
  72194. if (!VirtualJoystick.vjCanvas) {
  72195. window.addEventListener("resize", this._onResize, false);
  72196. VirtualJoystick.vjCanvas = document.createElement("canvas");
  72197. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72198. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72199. VirtualJoystick.vjCanvas.width = window.innerWidth;
  72200. VirtualJoystick.vjCanvas.height = window.innerHeight;
  72201. VirtualJoystick.vjCanvas.style.width = "100%";
  72202. VirtualJoystick.vjCanvas.style.height = "100%";
  72203. VirtualJoystick.vjCanvas.style.position = "absolute";
  72204. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  72205. VirtualJoystick.vjCanvas.style.top = "0px";
  72206. VirtualJoystick.vjCanvas.style.left = "0px";
  72207. VirtualJoystick.vjCanvas.style.zIndex = "5";
  72208. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  72209. // Support for jQuery PEP polyfill
  72210. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  72211. var context = VirtualJoystick.vjCanvas.getContext('2d');
  72212. if (!context) {
  72213. throw new Error("Unable to create canvas for virtual joystick");
  72214. }
  72215. VirtualJoystick.vjCanvasContext = context;
  72216. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  72217. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72218. document.body.appendChild(VirtualJoystick.vjCanvas);
  72219. }
  72220. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  72221. this.pressed = false;
  72222. // default joystick color
  72223. this._joystickColor = "cyan";
  72224. this._joystickPointerID = -1;
  72225. // current joystick position
  72226. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  72227. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  72228. // origin joystick position
  72229. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  72230. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  72231. this._onPointerDownHandlerRef = function (evt) {
  72232. _this._onPointerDown(evt);
  72233. };
  72234. this._onPointerMoveHandlerRef = function (evt) {
  72235. _this._onPointerMove(evt);
  72236. };
  72237. this._onPointerUpHandlerRef = function (evt) {
  72238. _this._onPointerUp(evt);
  72239. };
  72240. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  72241. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  72242. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  72243. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  72244. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  72245. evt.preventDefault(); // Disables system menu
  72246. }, false);
  72247. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72248. }
  72249. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  72250. this._joystickSensibility = newJoystickSensibility;
  72251. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72252. };
  72253. VirtualJoystick.prototype._onPointerDown = function (e) {
  72254. var positionOnScreenCondition;
  72255. e.preventDefault();
  72256. if (this._leftJoystick === true) {
  72257. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  72258. }
  72259. else {
  72260. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  72261. }
  72262. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  72263. // First contact will be dedicated to the virtual joystick
  72264. this._joystickPointerID = e.pointerId;
  72265. this._joystickPointerStartPos.x = e.clientX;
  72266. this._joystickPointerStartPos.y = e.clientY;
  72267. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  72268. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  72269. this._deltaJoystickVector.x = 0;
  72270. this._deltaJoystickVector.y = 0;
  72271. this.pressed = true;
  72272. this._touches.add(e.pointerId.toString(), e);
  72273. }
  72274. else {
  72275. // You can only trigger the action buttons with a joystick declared
  72276. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  72277. this._action();
  72278. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  72279. }
  72280. }
  72281. };
  72282. VirtualJoystick.prototype._onPointerMove = function (e) {
  72283. // If the current pointer is the one associated to the joystick (first touch contact)
  72284. if (this._joystickPointerID == e.pointerId) {
  72285. this._joystickPointerPos.x = e.clientX;
  72286. this._joystickPointerPos.y = e.clientY;
  72287. this._deltaJoystickVector = this._joystickPointerPos.clone();
  72288. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  72289. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  72290. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  72291. switch (this._axisTargetedByLeftAndRight) {
  72292. case JoystickAxis.X:
  72293. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  72294. break;
  72295. case JoystickAxis.Y:
  72296. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  72297. break;
  72298. case JoystickAxis.Z:
  72299. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  72300. break;
  72301. }
  72302. var directionUpDown = this.reverseUpDown ? 1 : -1;
  72303. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  72304. switch (this._axisTargetedByUpAndDown) {
  72305. case JoystickAxis.X:
  72306. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  72307. break;
  72308. case JoystickAxis.Y:
  72309. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  72310. break;
  72311. case JoystickAxis.Z:
  72312. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  72313. break;
  72314. }
  72315. }
  72316. else {
  72317. var data = this._touches.get(e.pointerId.toString());
  72318. if (data) {
  72319. data.x = e.clientX;
  72320. data.y = e.clientY;
  72321. }
  72322. }
  72323. };
  72324. VirtualJoystick.prototype._onPointerUp = function (e) {
  72325. if (this._joystickPointerID == e.pointerId) {
  72326. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  72327. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  72328. this._joystickPointerID = -1;
  72329. this.pressed = false;
  72330. }
  72331. else {
  72332. var touch = this._touches.get(e.pointerId.toString());
  72333. if (touch) {
  72334. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72335. }
  72336. }
  72337. this._deltaJoystickVector.x = 0;
  72338. this._deltaJoystickVector.y = 0;
  72339. this._touches.remove(e.pointerId.toString());
  72340. };
  72341. /**
  72342. * Change the color of the virtual joystick
  72343. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  72344. */
  72345. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  72346. this._joystickColor = newColor;
  72347. };
  72348. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  72349. this._action = action;
  72350. };
  72351. // Define which axis you'd like to control for left & right
  72352. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  72353. switch (axis) {
  72354. case JoystickAxis.X:
  72355. case JoystickAxis.Y:
  72356. case JoystickAxis.Z:
  72357. this._axisTargetedByLeftAndRight = axis;
  72358. break;
  72359. default:
  72360. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72361. break;
  72362. }
  72363. };
  72364. // Define which axis you'd like to control for up & down
  72365. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  72366. switch (axis) {
  72367. case JoystickAxis.X:
  72368. case JoystickAxis.Y:
  72369. case JoystickAxis.Z:
  72370. this._axisTargetedByUpAndDown = axis;
  72371. break;
  72372. default:
  72373. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72374. break;
  72375. }
  72376. };
  72377. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  72378. var _this = this;
  72379. if (this.pressed) {
  72380. this._touches.forEach(function (key, touch) {
  72381. if (touch.pointerId === _this._joystickPointerID) {
  72382. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  72383. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  72384. VirtualJoystick.vjCanvasContext.beginPath();
  72385. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72386. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  72388. VirtualJoystick.vjCanvasContext.stroke();
  72389. VirtualJoystick.vjCanvasContext.closePath();
  72390. VirtualJoystick.vjCanvasContext.beginPath();
  72391. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72392. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72393. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  72394. VirtualJoystick.vjCanvasContext.stroke();
  72395. VirtualJoystick.vjCanvasContext.closePath();
  72396. VirtualJoystick.vjCanvasContext.beginPath();
  72397. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72398. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  72399. VirtualJoystick.vjCanvasContext.stroke();
  72400. VirtualJoystick.vjCanvasContext.closePath();
  72401. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  72402. }
  72403. else {
  72404. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72405. VirtualJoystick.vjCanvasContext.beginPath();
  72406. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  72407. VirtualJoystick.vjCanvasContext.beginPath();
  72408. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  72409. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72410. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  72411. VirtualJoystick.vjCanvasContext.stroke();
  72412. VirtualJoystick.vjCanvasContext.closePath();
  72413. touch.prevX = touch.x;
  72414. touch.prevY = touch.y;
  72415. }
  72416. ;
  72417. });
  72418. }
  72419. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72420. };
  72421. VirtualJoystick.prototype.releaseCanvas = function () {
  72422. if (VirtualJoystick.vjCanvas) {
  72423. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  72424. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  72425. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  72426. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  72427. window.removeEventListener("resize", this._onResize);
  72428. document.body.removeChild(VirtualJoystick.vjCanvas);
  72429. VirtualJoystick.vjCanvas = null;
  72430. }
  72431. };
  72432. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  72433. VirtualJoystick._globalJoystickIndex = 0;
  72434. return VirtualJoystick;
  72435. }());
  72436. BABYLON.VirtualJoystick = VirtualJoystick;
  72437. })(BABYLON || (BABYLON = {}));
  72438. //# sourceMappingURL=babylon.virtualJoystick.js.map
  72439. var BABYLON;
  72440. (function (BABYLON) {
  72441. // We're mainly based on the logic defined into the FreeCamera code
  72442. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  72443. __extends(VirtualJoysticksCamera, _super);
  72444. function VirtualJoysticksCamera(name, position, scene) {
  72445. var _this = _super.call(this, name, position, scene) || this;
  72446. _this.inputs.addVirtualJoystick();
  72447. return _this;
  72448. }
  72449. VirtualJoysticksCamera.prototype.getClassName = function () {
  72450. return "VirtualJoysticksCamera";
  72451. };
  72452. return VirtualJoysticksCamera;
  72453. }(BABYLON.FreeCamera));
  72454. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  72455. })(BABYLON || (BABYLON = {}));
  72456. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  72457. var BABYLON;
  72458. (function (BABYLON) {
  72459. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  72460. function FreeCameraVirtualJoystickInput() {
  72461. }
  72462. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  72463. return this._leftjoystick;
  72464. };
  72465. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  72466. return this._rightjoystick;
  72467. };
  72468. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  72469. if (this._leftjoystick) {
  72470. var camera = this.camera;
  72471. var speed = camera._computeLocalCameraSpeed() * 50;
  72472. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  72473. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  72474. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  72475. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  72476. if (!this._leftjoystick.pressed) {
  72477. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  72478. }
  72479. if (!this._rightjoystick.pressed) {
  72480. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  72481. }
  72482. }
  72483. };
  72484. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  72485. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  72486. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  72487. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  72488. this._leftjoystick.setJoystickSensibility(0.15);
  72489. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  72490. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  72491. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  72492. this._rightjoystick.reverseUpDown = true;
  72493. this._rightjoystick.setJoystickSensibility(0.05);
  72494. this._rightjoystick.setJoystickColor("yellow");
  72495. };
  72496. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  72497. this._leftjoystick.releaseCanvas();
  72498. this._rightjoystick.releaseCanvas();
  72499. };
  72500. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  72501. return "FreeCameraVirtualJoystickInput";
  72502. };
  72503. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  72504. return "virtualJoystick";
  72505. };
  72506. return FreeCameraVirtualJoystickInput;
  72507. }());
  72508. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  72509. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  72510. })(BABYLON || (BABYLON = {}));
  72511. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  72512. var BABYLON;
  72513. (function (BABYLON) {
  72514. var SimplificationSettings = /** @class */ (function () {
  72515. function SimplificationSettings(quality, distance, optimizeMesh) {
  72516. this.quality = quality;
  72517. this.distance = distance;
  72518. this.optimizeMesh = optimizeMesh;
  72519. }
  72520. return SimplificationSettings;
  72521. }());
  72522. BABYLON.SimplificationSettings = SimplificationSettings;
  72523. var SimplificationQueue = /** @class */ (function () {
  72524. function SimplificationQueue() {
  72525. this.running = false;
  72526. this._simplificationArray = [];
  72527. }
  72528. SimplificationQueue.prototype.addTask = function (task) {
  72529. this._simplificationArray.push(task);
  72530. };
  72531. SimplificationQueue.prototype.executeNext = function () {
  72532. var task = this._simplificationArray.pop();
  72533. if (task) {
  72534. this.running = true;
  72535. this.runSimplification(task);
  72536. }
  72537. else {
  72538. this.running = false;
  72539. }
  72540. };
  72541. SimplificationQueue.prototype.runSimplification = function (task) {
  72542. var _this = this;
  72543. if (task.parallelProcessing) {
  72544. //parallel simplifier
  72545. task.settings.forEach(function (setting) {
  72546. var simplifier = _this.getSimplifier(task);
  72547. simplifier.simplify(setting, function (newMesh) {
  72548. task.mesh.addLODLevel(setting.distance, newMesh);
  72549. newMesh.isVisible = true;
  72550. //check if it is the last
  72551. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  72552. //all done, run the success callback.
  72553. task.successCallback();
  72554. }
  72555. _this.executeNext();
  72556. });
  72557. });
  72558. }
  72559. else {
  72560. //single simplifier.
  72561. var simplifier = this.getSimplifier(task);
  72562. var runDecimation = function (setting, callback) {
  72563. simplifier.simplify(setting, function (newMesh) {
  72564. task.mesh.addLODLevel(setting.distance, newMesh);
  72565. newMesh.isVisible = true;
  72566. //run the next quality level
  72567. callback();
  72568. });
  72569. };
  72570. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  72571. runDecimation(task.settings[loop.index], function () {
  72572. loop.executeNext();
  72573. });
  72574. }, function () {
  72575. //execution ended, run the success callback.
  72576. if (task.successCallback) {
  72577. task.successCallback();
  72578. }
  72579. _this.executeNext();
  72580. });
  72581. }
  72582. };
  72583. SimplificationQueue.prototype.getSimplifier = function (task) {
  72584. switch (task.simplificationType) {
  72585. case SimplificationType.QUADRATIC:
  72586. default:
  72587. return new QuadraticErrorSimplification(task.mesh);
  72588. }
  72589. };
  72590. return SimplificationQueue;
  72591. }());
  72592. BABYLON.SimplificationQueue = SimplificationQueue;
  72593. /**
  72594. * The implemented types of simplification.
  72595. * At the moment only Quadratic Error Decimation is implemented.
  72596. */
  72597. var SimplificationType;
  72598. (function (SimplificationType) {
  72599. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  72600. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  72601. var DecimationTriangle = /** @class */ (function () {
  72602. function DecimationTriangle(vertices) {
  72603. this.vertices = vertices;
  72604. this.error = new Array(4);
  72605. this.deleted = false;
  72606. this.isDirty = false;
  72607. this.deletePending = false;
  72608. this.borderFactor = 0;
  72609. }
  72610. return DecimationTriangle;
  72611. }());
  72612. BABYLON.DecimationTriangle = DecimationTriangle;
  72613. var DecimationVertex = /** @class */ (function () {
  72614. function DecimationVertex(position, id) {
  72615. this.position = position;
  72616. this.id = id;
  72617. this.isBorder = true;
  72618. this.q = new QuadraticMatrix();
  72619. this.triangleCount = 0;
  72620. this.triangleStart = 0;
  72621. this.originalOffsets = [];
  72622. }
  72623. DecimationVertex.prototype.updatePosition = function (newPosition) {
  72624. this.position.copyFrom(newPosition);
  72625. };
  72626. return DecimationVertex;
  72627. }());
  72628. BABYLON.DecimationVertex = DecimationVertex;
  72629. var QuadraticMatrix = /** @class */ (function () {
  72630. function QuadraticMatrix(data) {
  72631. this.data = new Array(10);
  72632. for (var i = 0; i < 10; ++i) {
  72633. if (data && data[i]) {
  72634. this.data[i] = data[i];
  72635. }
  72636. else {
  72637. this.data[i] = 0;
  72638. }
  72639. }
  72640. }
  72641. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  72642. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  72643. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  72644. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  72645. return det;
  72646. };
  72647. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  72648. for (var i = 0; i < 10; ++i) {
  72649. this.data[i] += matrix.data[i];
  72650. }
  72651. };
  72652. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  72653. for (var i = 0; i < 10; ++i) {
  72654. this.data[i] += data[i];
  72655. }
  72656. };
  72657. QuadraticMatrix.prototype.add = function (matrix) {
  72658. var m = new QuadraticMatrix();
  72659. for (var i = 0; i < 10; ++i) {
  72660. m.data[i] = this.data[i] + matrix.data[i];
  72661. }
  72662. return m;
  72663. };
  72664. QuadraticMatrix.FromData = function (a, b, c, d) {
  72665. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  72666. };
  72667. //returning an array to avoid garbage collection
  72668. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  72669. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  72670. };
  72671. return QuadraticMatrix;
  72672. }());
  72673. BABYLON.QuadraticMatrix = QuadraticMatrix;
  72674. var Reference = /** @class */ (function () {
  72675. function Reference(vertexId, triangleId) {
  72676. this.vertexId = vertexId;
  72677. this.triangleId = triangleId;
  72678. }
  72679. return Reference;
  72680. }());
  72681. BABYLON.Reference = Reference;
  72682. /**
  72683. * An implementation of the Quadratic Error simplification algorithm.
  72684. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  72685. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  72686. * @author RaananW
  72687. */
  72688. var QuadraticErrorSimplification = /** @class */ (function () {
  72689. function QuadraticErrorSimplification(_mesh) {
  72690. this._mesh = _mesh;
  72691. this.syncIterations = 5000;
  72692. this.aggressiveness = 7;
  72693. this.decimationIterations = 100;
  72694. this.boundingBoxEpsilon = BABYLON.Epsilon;
  72695. }
  72696. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  72697. var _this = this;
  72698. this.initDecimatedMesh();
  72699. //iterating through the submeshes array, one after the other.
  72700. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  72701. _this.initWithMesh(loop.index, function () {
  72702. _this.runDecimation(settings, loop.index, function () {
  72703. loop.executeNext();
  72704. });
  72705. }, settings.optimizeMesh);
  72706. }, function () {
  72707. setTimeout(function () {
  72708. successCallback(_this._reconstructedMesh);
  72709. }, 0);
  72710. });
  72711. };
  72712. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  72713. var _this = this;
  72714. var targetCount = ~~(this.triangles.length * settings.quality);
  72715. var deletedTriangles = 0;
  72716. var triangleCount = this.triangles.length;
  72717. var iterationFunction = function (iteration, callback) {
  72718. setTimeout(function () {
  72719. if (iteration % 5 === 0) {
  72720. _this.updateMesh(iteration === 0);
  72721. }
  72722. for (var i = 0; i < _this.triangles.length; ++i) {
  72723. _this.triangles[i].isDirty = false;
  72724. }
  72725. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  72726. var trianglesIterator = function (i) {
  72727. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  72728. var t = _this.triangles[tIdx];
  72729. if (!t)
  72730. return;
  72731. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  72732. return;
  72733. }
  72734. for (var j = 0; j < 3; ++j) {
  72735. if (t.error[j] < threshold) {
  72736. var deleted0 = [];
  72737. var deleted1 = [];
  72738. var v0 = t.vertices[j];
  72739. var v1 = t.vertices[(j + 1) % 3];
  72740. if (v0.isBorder || v1.isBorder)
  72741. continue;
  72742. var p = BABYLON.Vector3.Zero();
  72743. var n = BABYLON.Vector3.Zero();
  72744. var uv = BABYLON.Vector2.Zero();
  72745. var color = new BABYLON.Color4(0, 0, 0, 1);
  72746. _this.calculateError(v0, v1, p, n, uv, color);
  72747. var delTr = new Array();
  72748. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  72749. continue;
  72750. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  72751. continue;
  72752. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  72753. continue;
  72754. var uniqueArray = new Array();
  72755. delTr.forEach(function (deletedT) {
  72756. if (uniqueArray.indexOf(deletedT) === -1) {
  72757. deletedT.deletePending = true;
  72758. uniqueArray.push(deletedT);
  72759. }
  72760. });
  72761. if (uniqueArray.length % 2 !== 0) {
  72762. continue;
  72763. }
  72764. v0.q = v1.q.add(v0.q);
  72765. v0.updatePosition(p);
  72766. var tStart = _this.references.length;
  72767. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  72768. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  72769. var tCount = _this.references.length - tStart;
  72770. if (tCount <= v0.triangleCount) {
  72771. if (tCount) {
  72772. for (var c = 0; c < tCount; c++) {
  72773. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  72774. }
  72775. }
  72776. }
  72777. else {
  72778. v0.triangleStart = tStart;
  72779. }
  72780. v0.triangleCount = tCount;
  72781. break;
  72782. }
  72783. }
  72784. };
  72785. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  72786. }, 0);
  72787. };
  72788. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  72789. if (triangleCount - deletedTriangles <= targetCount)
  72790. loop.breakLoop();
  72791. else {
  72792. iterationFunction(loop.index, function () {
  72793. loop.executeNext();
  72794. });
  72795. }
  72796. }, function () {
  72797. setTimeout(function () {
  72798. //reconstruct this part of the mesh
  72799. _this.reconstructMesh(submeshIndex);
  72800. successCallback();
  72801. }, 0);
  72802. });
  72803. };
  72804. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  72805. var _this = this;
  72806. this.vertices = [];
  72807. this.triangles = [];
  72808. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72809. var indices = this._mesh.getIndices();
  72810. var submesh = this._mesh.subMeshes[submeshIndex];
  72811. var findInVertices = function (positionToSearch) {
  72812. if (optimizeMesh) {
  72813. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  72814. if (_this.vertices[ii].position.equals(positionToSearch)) {
  72815. return _this.vertices[ii];
  72816. }
  72817. }
  72818. }
  72819. return null;
  72820. };
  72821. var vertexReferences = [];
  72822. var vertexInit = function (i) {
  72823. if (!positionData) {
  72824. return;
  72825. }
  72826. var offset = i + submesh.verticesStart;
  72827. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  72828. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  72829. vertex.originalOffsets.push(offset);
  72830. if (vertex.id === _this.vertices.length) {
  72831. _this.vertices.push(vertex);
  72832. }
  72833. vertexReferences.push(vertex.id);
  72834. };
  72835. //var totalVertices = mesh.getTotalVertices();
  72836. var totalVertices = submesh.verticesCount;
  72837. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  72838. var indicesInit = function (i) {
  72839. if (!indices) {
  72840. return;
  72841. }
  72842. var offset = (submesh.indexStart / 3) + i;
  72843. var pos = (offset * 3);
  72844. var i0 = indices[pos + 0];
  72845. var i1 = indices[pos + 1];
  72846. var i2 = indices[pos + 2];
  72847. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  72848. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  72849. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  72850. var triangle = new DecimationTriangle([v0, v1, v2]);
  72851. triangle.originalOffset = pos;
  72852. _this.triangles.push(triangle);
  72853. };
  72854. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  72855. _this.init(callback);
  72856. });
  72857. });
  72858. };
  72859. QuadraticErrorSimplification.prototype.init = function (callback) {
  72860. var _this = this;
  72861. var triangleInit1 = function (i) {
  72862. var t = _this.triangles[i];
  72863. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  72864. for (var j = 0; j < 3; j++) {
  72865. 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))));
  72866. }
  72867. };
  72868. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  72869. var triangleInit2 = function (i) {
  72870. var t = _this.triangles[i];
  72871. for (var j = 0; j < 3; ++j) {
  72872. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  72873. }
  72874. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  72875. };
  72876. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  72877. callback();
  72878. });
  72879. });
  72880. };
  72881. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  72882. var newTriangles = [];
  72883. var i;
  72884. for (i = 0; i < this.vertices.length; ++i) {
  72885. this.vertices[i].triangleCount = 0;
  72886. }
  72887. var t;
  72888. var j;
  72889. for (i = 0; i < this.triangles.length; ++i) {
  72890. if (!this.triangles[i].deleted) {
  72891. t = this.triangles[i];
  72892. for (j = 0; j < 3; ++j) {
  72893. t.vertices[j].triangleCount = 1;
  72894. }
  72895. newTriangles.push(t);
  72896. }
  72897. }
  72898. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  72899. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  72900. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  72901. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  72902. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  72903. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72904. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  72905. var vertexCount = 0;
  72906. for (i = 0; i < this.vertices.length; ++i) {
  72907. var vertex = this.vertices[i];
  72908. vertex.id = vertexCount;
  72909. if (vertex.triangleCount) {
  72910. vertex.originalOffsets.forEach(function (originalOffset) {
  72911. if (!normalData) {
  72912. return;
  72913. }
  72914. newPositionData.push(vertex.position.x);
  72915. newPositionData.push(vertex.position.y);
  72916. newPositionData.push(vertex.position.z);
  72917. newNormalData.push(normalData[originalOffset * 3]);
  72918. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  72919. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  72920. if (uvs && uvs.length) {
  72921. newUVsData.push(uvs[(originalOffset * 2)]);
  72922. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  72923. }
  72924. else if (colorsData && colorsData.length) {
  72925. newColorsData.push(colorsData[(originalOffset * 4)]);
  72926. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  72927. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  72928. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  72929. }
  72930. ++vertexCount;
  72931. });
  72932. }
  72933. }
  72934. var startingIndex = this._reconstructedMesh.getTotalIndices();
  72935. var startingVertex = this._reconstructedMesh.getTotalVertices();
  72936. var submeshesArray = this._reconstructedMesh.subMeshes;
  72937. this._reconstructedMesh.subMeshes = [];
  72938. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  72939. var originalIndices = this._mesh.getIndices();
  72940. for (i = 0; i < newTriangles.length; ++i) {
  72941. t = newTriangles[i]; //now get the new referencing point for each vertex
  72942. [0, 1, 2].forEach(function (idx) {
  72943. var id = originalIndices[t.originalOffset + idx];
  72944. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  72945. if (offset < 0)
  72946. offset = 0;
  72947. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  72948. });
  72949. }
  72950. //overwriting the old vertex buffers and indices.
  72951. this._reconstructedMesh.setIndices(newIndicesArray);
  72952. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  72953. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  72954. if (newUVsData.length > 0)
  72955. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  72956. if (newColorsData.length > 0)
  72957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  72958. //create submesh
  72959. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  72960. if (submeshIndex > 0) {
  72961. this._reconstructedMesh.subMeshes = [];
  72962. submeshesArray.forEach(function (submesh) {
  72963. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  72964. });
  72965. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  72966. }
  72967. };
  72968. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  72969. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  72970. this._reconstructedMesh.material = this._mesh.material;
  72971. this._reconstructedMesh.parent = this._mesh.parent;
  72972. this._reconstructedMesh.isVisible = false;
  72973. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  72974. };
  72975. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  72976. for (var i = 0; i < vertex1.triangleCount; ++i) {
  72977. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  72978. if (t.deleted)
  72979. continue;
  72980. var s = this.references[vertex1.triangleStart + i].vertexId;
  72981. var v1 = t.vertices[(s + 1) % 3];
  72982. var v2 = t.vertices[(s + 2) % 3];
  72983. if ((v1 === vertex2 || v2 === vertex2)) {
  72984. deletedArray[i] = true;
  72985. delTr.push(t);
  72986. continue;
  72987. }
  72988. var d1 = v1.position.subtract(point);
  72989. d1 = d1.normalize();
  72990. var d2 = v2.position.subtract(point);
  72991. d2 = d2.normalize();
  72992. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  72993. return true;
  72994. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  72995. deletedArray[i] = false;
  72996. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  72997. return true;
  72998. }
  72999. return false;
  73000. };
  73001. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  73002. var newDeleted = deletedTriangles;
  73003. for (var i = 0; i < vertex.triangleCount; ++i) {
  73004. var ref = this.references[vertex.triangleStart + i];
  73005. var t = this.triangles[ref.triangleId];
  73006. if (t.deleted)
  73007. continue;
  73008. if (deletedArray[i] && t.deletePending) {
  73009. t.deleted = true;
  73010. newDeleted++;
  73011. continue;
  73012. }
  73013. t.vertices[ref.vertexId] = origVertex;
  73014. t.isDirty = true;
  73015. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  73016. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  73017. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  73018. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73019. this.references.push(ref);
  73020. }
  73021. return newDeleted;
  73022. };
  73023. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  73024. for (var i = 0; i < this.vertices.length; ++i) {
  73025. var vCount = [];
  73026. var vId = [];
  73027. var v = this.vertices[i];
  73028. var j;
  73029. for (j = 0; j < v.triangleCount; ++j) {
  73030. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  73031. for (var ii = 0; ii < 3; ii++) {
  73032. var ofs = 0;
  73033. var vv = triangle.vertices[ii];
  73034. while (ofs < vCount.length) {
  73035. if (vId[ofs] === vv.id)
  73036. break;
  73037. ++ofs;
  73038. }
  73039. if (ofs === vCount.length) {
  73040. vCount.push(1);
  73041. vId.push(vv.id);
  73042. }
  73043. else {
  73044. vCount[ofs]++;
  73045. }
  73046. }
  73047. }
  73048. for (j = 0; j < vCount.length; ++j) {
  73049. if (vCount[j] === 1) {
  73050. this.vertices[vId[j]].isBorder = true;
  73051. }
  73052. else {
  73053. this.vertices[vId[j]].isBorder = false;
  73054. }
  73055. }
  73056. }
  73057. };
  73058. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  73059. if (identifyBorders === void 0) { identifyBorders = false; }
  73060. var i;
  73061. if (!identifyBorders) {
  73062. var newTrianglesVector = [];
  73063. for (i = 0; i < this.triangles.length; ++i) {
  73064. if (!this.triangles[i].deleted) {
  73065. newTrianglesVector.push(this.triangles[i]);
  73066. }
  73067. }
  73068. this.triangles = newTrianglesVector;
  73069. }
  73070. for (i = 0; i < this.vertices.length; ++i) {
  73071. this.vertices[i].triangleCount = 0;
  73072. this.vertices[i].triangleStart = 0;
  73073. }
  73074. var t;
  73075. var j;
  73076. var v;
  73077. for (i = 0; i < this.triangles.length; ++i) {
  73078. t = this.triangles[i];
  73079. for (j = 0; j < 3; ++j) {
  73080. v = t.vertices[j];
  73081. v.triangleCount++;
  73082. }
  73083. }
  73084. var tStart = 0;
  73085. for (i = 0; i < this.vertices.length; ++i) {
  73086. this.vertices[i].triangleStart = tStart;
  73087. tStart += this.vertices[i].triangleCount;
  73088. this.vertices[i].triangleCount = 0;
  73089. }
  73090. var newReferences = new Array(this.triangles.length * 3);
  73091. for (i = 0; i < this.triangles.length; ++i) {
  73092. t = this.triangles[i];
  73093. for (j = 0; j < 3; ++j) {
  73094. v = t.vertices[j];
  73095. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  73096. v.triangleCount++;
  73097. }
  73098. }
  73099. this.references = newReferences;
  73100. if (identifyBorders) {
  73101. this.identifyBorder();
  73102. }
  73103. };
  73104. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  73105. var x = point.x;
  73106. var y = point.y;
  73107. var z = point.z;
  73108. 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
  73109. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  73110. };
  73111. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  73112. var q = vertex1.q.add(vertex2.q);
  73113. var border = vertex1.isBorder && vertex2.isBorder;
  73114. var error = 0;
  73115. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  73116. if (qDet !== 0 && !border) {
  73117. if (!pointResult) {
  73118. pointResult = BABYLON.Vector3.Zero();
  73119. }
  73120. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  73121. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  73122. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  73123. error = this.vertexError(q, pointResult);
  73124. }
  73125. else {
  73126. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  73127. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  73128. var error1 = this.vertexError(q, vertex1.position);
  73129. var error2 = this.vertexError(q, vertex2.position);
  73130. var error3 = this.vertexError(q, p3);
  73131. error = Math.min(error1, error2, error3);
  73132. if (error === error1) {
  73133. if (pointResult) {
  73134. pointResult.copyFrom(vertex1.position);
  73135. }
  73136. }
  73137. else if (error === error2) {
  73138. if (pointResult) {
  73139. pointResult.copyFrom(vertex2.position);
  73140. }
  73141. }
  73142. else {
  73143. if (pointResult) {
  73144. pointResult.copyFrom(p3);
  73145. }
  73146. }
  73147. }
  73148. return error;
  73149. };
  73150. return QuadraticErrorSimplification;
  73151. }());
  73152. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  73153. })(BABYLON || (BABYLON = {}));
  73154. //# sourceMappingURL=babylon.meshSimplification.js.map
  73155. var BABYLON;
  73156. (function (BABYLON) {
  73157. var Internals;
  73158. (function (Internals) {
  73159. var MeshLODLevel = /** @class */ (function () {
  73160. function MeshLODLevel(distance, mesh) {
  73161. this.distance = distance;
  73162. this.mesh = mesh;
  73163. }
  73164. return MeshLODLevel;
  73165. }());
  73166. Internals.MeshLODLevel = MeshLODLevel;
  73167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  73168. })(BABYLON || (BABYLON = {}));
  73169. //# sourceMappingURL=babylon.meshLODLevel.js.map
  73170. var BABYLON;
  73171. (function (BABYLON) {
  73172. // Standard optimizations
  73173. var SceneOptimization = /** @class */ (function () {
  73174. function SceneOptimization(priority) {
  73175. if (priority === void 0) { priority = 0; }
  73176. this.priority = priority;
  73177. this.apply = function (scene) {
  73178. return true; // Return true if everything that can be done was applied
  73179. };
  73180. }
  73181. return SceneOptimization;
  73182. }());
  73183. BABYLON.SceneOptimization = SceneOptimization;
  73184. var TextureOptimization = /** @class */ (function (_super) {
  73185. __extends(TextureOptimization, _super);
  73186. function TextureOptimization(priority, maximumSize) {
  73187. if (priority === void 0) { priority = 0; }
  73188. if (maximumSize === void 0) { maximumSize = 1024; }
  73189. var _this = _super.call(this, priority) || this;
  73190. _this.priority = priority;
  73191. _this.maximumSize = maximumSize;
  73192. _this.apply = function (scene) {
  73193. var allDone = true;
  73194. for (var index = 0; index < scene.textures.length; index++) {
  73195. var texture = scene.textures[index];
  73196. if (!texture.canRescale || texture.getContext) {
  73197. continue;
  73198. }
  73199. var currentSize = texture.getSize();
  73200. var maxDimension = Math.max(currentSize.width, currentSize.height);
  73201. if (maxDimension > _this.maximumSize) {
  73202. texture.scale(0.5);
  73203. allDone = false;
  73204. }
  73205. }
  73206. return allDone;
  73207. };
  73208. return _this;
  73209. }
  73210. return TextureOptimization;
  73211. }(SceneOptimization));
  73212. BABYLON.TextureOptimization = TextureOptimization;
  73213. var HardwareScalingOptimization = /** @class */ (function (_super) {
  73214. __extends(HardwareScalingOptimization, _super);
  73215. function HardwareScalingOptimization(priority, maximumScale) {
  73216. if (priority === void 0) { priority = 0; }
  73217. if (maximumScale === void 0) { maximumScale = 2; }
  73218. var _this = _super.call(this, priority) || this;
  73219. _this.priority = priority;
  73220. _this.maximumScale = maximumScale;
  73221. _this._currentScale = 1;
  73222. _this.apply = function (scene) {
  73223. _this._currentScale++;
  73224. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  73225. return _this._currentScale >= _this.maximumScale;
  73226. };
  73227. return _this;
  73228. }
  73229. return HardwareScalingOptimization;
  73230. }(SceneOptimization));
  73231. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  73232. var ShadowsOptimization = /** @class */ (function (_super) {
  73233. __extends(ShadowsOptimization, _super);
  73234. function ShadowsOptimization() {
  73235. var _this = _super !== null && _super.apply(this, arguments) || this;
  73236. _this.apply = function (scene) {
  73237. scene.shadowsEnabled = false;
  73238. return true;
  73239. };
  73240. return _this;
  73241. }
  73242. return ShadowsOptimization;
  73243. }(SceneOptimization));
  73244. BABYLON.ShadowsOptimization = ShadowsOptimization;
  73245. var PostProcessesOptimization = /** @class */ (function (_super) {
  73246. __extends(PostProcessesOptimization, _super);
  73247. function PostProcessesOptimization() {
  73248. var _this = _super !== null && _super.apply(this, arguments) || this;
  73249. _this.apply = function (scene) {
  73250. scene.postProcessesEnabled = false;
  73251. return true;
  73252. };
  73253. return _this;
  73254. }
  73255. return PostProcessesOptimization;
  73256. }(SceneOptimization));
  73257. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  73258. var LensFlaresOptimization = /** @class */ (function (_super) {
  73259. __extends(LensFlaresOptimization, _super);
  73260. function LensFlaresOptimization() {
  73261. var _this = _super !== null && _super.apply(this, arguments) || this;
  73262. _this.apply = function (scene) {
  73263. scene.lensFlaresEnabled = false;
  73264. return true;
  73265. };
  73266. return _this;
  73267. }
  73268. return LensFlaresOptimization;
  73269. }(SceneOptimization));
  73270. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  73271. var ParticlesOptimization = /** @class */ (function (_super) {
  73272. __extends(ParticlesOptimization, _super);
  73273. function ParticlesOptimization() {
  73274. var _this = _super !== null && _super.apply(this, arguments) || this;
  73275. _this.apply = function (scene) {
  73276. scene.particlesEnabled = false;
  73277. return true;
  73278. };
  73279. return _this;
  73280. }
  73281. return ParticlesOptimization;
  73282. }(SceneOptimization));
  73283. BABYLON.ParticlesOptimization = ParticlesOptimization;
  73284. var RenderTargetsOptimization = /** @class */ (function (_super) {
  73285. __extends(RenderTargetsOptimization, _super);
  73286. function RenderTargetsOptimization() {
  73287. var _this = _super !== null && _super.apply(this, arguments) || this;
  73288. _this.apply = function (scene) {
  73289. scene.renderTargetsEnabled = false;
  73290. return true;
  73291. };
  73292. return _this;
  73293. }
  73294. return RenderTargetsOptimization;
  73295. }(SceneOptimization));
  73296. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  73297. var MergeMeshesOptimization = /** @class */ (function (_super) {
  73298. __extends(MergeMeshesOptimization, _super);
  73299. function MergeMeshesOptimization() {
  73300. var _this = _super !== null && _super.apply(this, arguments) || this;
  73301. _this._canBeMerged = function (abstractMesh) {
  73302. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  73303. return false;
  73304. }
  73305. var mesh = abstractMesh;
  73306. if (!mesh.isVisible || !mesh.isEnabled()) {
  73307. return false;
  73308. }
  73309. if (mesh.instances.length > 0) {
  73310. return false;
  73311. }
  73312. if (mesh.skeleton || mesh.hasLODLevels) {
  73313. return false;
  73314. }
  73315. if (mesh.parent) {
  73316. return false;
  73317. }
  73318. return true;
  73319. };
  73320. _this.apply = function (scene, updateSelectionTree) {
  73321. var globalPool = scene.meshes.slice(0);
  73322. var globalLength = globalPool.length;
  73323. for (var index = 0; index < globalLength; index++) {
  73324. var currentPool = new Array();
  73325. var current = globalPool[index];
  73326. // Checks
  73327. if (!_this._canBeMerged(current)) {
  73328. continue;
  73329. }
  73330. currentPool.push(current);
  73331. // Find compatible meshes
  73332. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  73333. var otherMesh = globalPool[subIndex];
  73334. if (!_this._canBeMerged(otherMesh)) {
  73335. continue;
  73336. }
  73337. if (otherMesh.material !== current.material) {
  73338. continue;
  73339. }
  73340. if (otherMesh.checkCollisions !== current.checkCollisions) {
  73341. continue;
  73342. }
  73343. currentPool.push(otherMesh);
  73344. globalLength--;
  73345. globalPool.splice(subIndex, 1);
  73346. subIndex--;
  73347. }
  73348. if (currentPool.length < 2) {
  73349. continue;
  73350. }
  73351. // Merge meshes
  73352. BABYLON.Mesh.MergeMeshes(currentPool);
  73353. }
  73354. if (updateSelectionTree != undefined) {
  73355. if (updateSelectionTree) {
  73356. scene.createOrUpdateSelectionOctree();
  73357. }
  73358. }
  73359. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  73360. scene.createOrUpdateSelectionOctree();
  73361. }
  73362. return true;
  73363. };
  73364. return _this;
  73365. }
  73366. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  73367. get: function () {
  73368. return MergeMeshesOptimization._UpdateSelectionTree;
  73369. },
  73370. set: function (value) {
  73371. MergeMeshesOptimization._UpdateSelectionTree = value;
  73372. },
  73373. enumerable: true,
  73374. configurable: true
  73375. });
  73376. MergeMeshesOptimization._UpdateSelectionTree = false;
  73377. return MergeMeshesOptimization;
  73378. }(SceneOptimization));
  73379. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  73380. // Options
  73381. var SceneOptimizerOptions = /** @class */ (function () {
  73382. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  73383. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  73384. if (trackerDuration === void 0) { trackerDuration = 2000; }
  73385. this.targetFrameRate = targetFrameRate;
  73386. this.trackerDuration = trackerDuration;
  73387. this.optimizations = new Array();
  73388. }
  73389. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  73390. var result = new SceneOptimizerOptions(targetFrameRate);
  73391. var priority = 0;
  73392. result.optimizations.push(new MergeMeshesOptimization(priority));
  73393. result.optimizations.push(new ShadowsOptimization(priority));
  73394. result.optimizations.push(new LensFlaresOptimization(priority));
  73395. // Next priority
  73396. priority++;
  73397. result.optimizations.push(new PostProcessesOptimization(priority));
  73398. result.optimizations.push(new ParticlesOptimization(priority));
  73399. // Next priority
  73400. priority++;
  73401. result.optimizations.push(new TextureOptimization(priority, 1024));
  73402. return result;
  73403. };
  73404. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  73405. var result = new SceneOptimizerOptions(targetFrameRate);
  73406. var priority = 0;
  73407. result.optimizations.push(new MergeMeshesOptimization(priority));
  73408. result.optimizations.push(new ShadowsOptimization(priority));
  73409. result.optimizations.push(new LensFlaresOptimization(priority));
  73410. // Next priority
  73411. priority++;
  73412. result.optimizations.push(new PostProcessesOptimization(priority));
  73413. result.optimizations.push(new ParticlesOptimization(priority));
  73414. // Next priority
  73415. priority++;
  73416. result.optimizations.push(new TextureOptimization(priority, 512));
  73417. // Next priority
  73418. priority++;
  73419. result.optimizations.push(new RenderTargetsOptimization(priority));
  73420. // Next priority
  73421. priority++;
  73422. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  73423. return result;
  73424. };
  73425. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  73426. var result = new SceneOptimizerOptions(targetFrameRate);
  73427. var priority = 0;
  73428. result.optimizations.push(new MergeMeshesOptimization(priority));
  73429. result.optimizations.push(new ShadowsOptimization(priority));
  73430. result.optimizations.push(new LensFlaresOptimization(priority));
  73431. // Next priority
  73432. priority++;
  73433. result.optimizations.push(new PostProcessesOptimization(priority));
  73434. result.optimizations.push(new ParticlesOptimization(priority));
  73435. // Next priority
  73436. priority++;
  73437. result.optimizations.push(new TextureOptimization(priority, 256));
  73438. // Next priority
  73439. priority++;
  73440. result.optimizations.push(new RenderTargetsOptimization(priority));
  73441. // Next priority
  73442. priority++;
  73443. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  73444. return result;
  73445. };
  73446. return SceneOptimizerOptions;
  73447. }());
  73448. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  73449. // Scene optimizer tool
  73450. var SceneOptimizer = /** @class */ (function () {
  73451. function SceneOptimizer() {
  73452. }
  73453. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  73454. // TODO: add an epsilon
  73455. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  73456. if (onSuccess) {
  73457. onSuccess();
  73458. }
  73459. return;
  73460. }
  73461. // Apply current level of optimizations
  73462. var allDone = true;
  73463. var noOptimizationApplied = true;
  73464. for (var index = 0; index < options.optimizations.length; index++) {
  73465. var optimization = options.optimizations[index];
  73466. if (optimization.priority === currentPriorityLevel) {
  73467. noOptimizationApplied = false;
  73468. allDone = allDone && optimization.apply(scene);
  73469. }
  73470. }
  73471. // If no optimization was applied, this is a failure :(
  73472. if (noOptimizationApplied) {
  73473. if (onFailure) {
  73474. onFailure();
  73475. }
  73476. return;
  73477. }
  73478. // If all optimizations were done, move to next level
  73479. if (allDone) {
  73480. currentPriorityLevel++;
  73481. }
  73482. // Let's the system running for a specific amount of time before checking FPS
  73483. scene.executeWhenReady(function () {
  73484. setTimeout(function () {
  73485. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  73486. }, options.trackerDuration);
  73487. });
  73488. };
  73489. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  73490. if (!options) {
  73491. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  73492. }
  73493. // Let's the system running for a specific amount of time before checking FPS
  73494. scene.executeWhenReady(function () {
  73495. setTimeout(function () {
  73496. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  73497. }, options.trackerDuration);
  73498. });
  73499. };
  73500. return SceneOptimizer;
  73501. }());
  73502. BABYLON.SceneOptimizer = SceneOptimizer;
  73503. })(BABYLON || (BABYLON = {}));
  73504. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  73505. var BABYLON;
  73506. (function (BABYLON) {
  73507. var OutlineRenderer = /** @class */ (function () {
  73508. function OutlineRenderer(scene) {
  73509. this.zOffset = 1;
  73510. this._scene = scene;
  73511. }
  73512. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  73513. var _this = this;
  73514. if (useOverlay === void 0) { useOverlay = false; }
  73515. var scene = this._scene;
  73516. var engine = this._scene.getEngine();
  73517. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73518. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  73519. return;
  73520. }
  73521. var mesh = subMesh.getRenderingMesh();
  73522. var material = subMesh.getMaterial();
  73523. if (!material || !scene.activeCamera) {
  73524. return;
  73525. }
  73526. engine.enableEffect(this._effect);
  73527. // Logarithmic depth
  73528. if (material.useLogarithmicDepth) {
  73529. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  73530. }
  73531. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  73532. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  73533. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73534. // Bones
  73535. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73536. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73537. }
  73538. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73539. // Alpha test
  73540. if (material && material.needAlphaTesting()) {
  73541. var alphaTexture = material.getAlphaTestTexture();
  73542. if (alphaTexture) {
  73543. this._effect.setTexture("diffuseSampler", alphaTexture);
  73544. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73545. }
  73546. }
  73547. engine.setZOffset(-this.zOffset);
  73548. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  73549. engine.setZOffset(0);
  73550. };
  73551. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  73552. var defines = [];
  73553. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73554. var mesh = subMesh.getMesh();
  73555. var material = subMesh.getMaterial();
  73556. if (material) {
  73557. // Alpha test
  73558. if (material.needAlphaTesting()) {
  73559. defines.push("#define ALPHATEST");
  73560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73561. attribs.push(BABYLON.VertexBuffer.UVKind);
  73562. defines.push("#define UV1");
  73563. }
  73564. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73565. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73566. defines.push("#define UV2");
  73567. }
  73568. }
  73569. //Logarithmic depth
  73570. if (material.useLogarithmicDepth) {
  73571. defines.push("#define LOGARITHMICDEPTH");
  73572. }
  73573. }
  73574. // Bones
  73575. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73578. if (mesh.numBoneInfluencers > 4) {
  73579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73581. }
  73582. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73583. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73584. }
  73585. else {
  73586. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73587. }
  73588. // Instances
  73589. if (useInstances) {
  73590. defines.push("#define INSTANCES");
  73591. attribs.push("world0");
  73592. attribs.push("world1");
  73593. attribs.push("world2");
  73594. attribs.push("world3");
  73595. }
  73596. // Get correct effect
  73597. var join = defines.join("\n");
  73598. if (this._cachedDefines !== join) {
  73599. this._cachedDefines = join;
  73600. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  73601. }
  73602. return this._effect.isReady();
  73603. };
  73604. return OutlineRenderer;
  73605. }());
  73606. BABYLON.OutlineRenderer = OutlineRenderer;
  73607. })(BABYLON || (BABYLON = {}));
  73608. //# sourceMappingURL=babylon.outlineRenderer.js.map
  73609. var BABYLON;
  73610. (function (BABYLON) {
  73611. var FaceAdjacencies = /** @class */ (function () {
  73612. function FaceAdjacencies() {
  73613. this.edges = new Array();
  73614. this.edgesConnectedCount = 0;
  73615. }
  73616. return FaceAdjacencies;
  73617. }());
  73618. var EdgesRenderer = /** @class */ (function () {
  73619. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  73620. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  73621. if (epsilon === void 0) { epsilon = 0.95; }
  73622. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  73623. this.edgesWidthScalerForOrthographic = 1000.0;
  73624. this.edgesWidthScalerForPerspective = 50.0;
  73625. this._linesPositions = new Array();
  73626. this._linesNormals = new Array();
  73627. this._linesIndices = new Array();
  73628. this._buffers = {};
  73629. this._checkVerticesInsteadOfIndices = false;
  73630. this._source = source;
  73631. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  73632. this._epsilon = epsilon;
  73633. this._prepareRessources();
  73634. this._generateEdgesLines();
  73635. }
  73636. EdgesRenderer.prototype._prepareRessources = function () {
  73637. if (this._lineShader) {
  73638. return;
  73639. }
  73640. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  73641. attributes: ["position", "normal"],
  73642. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  73643. });
  73644. this._lineShader.disableDepthWrite = true;
  73645. this._lineShader.backFaceCulling = false;
  73646. };
  73647. EdgesRenderer.prototype._rebuild = function () {
  73648. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73649. if (buffer) {
  73650. buffer._rebuild();
  73651. }
  73652. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73653. if (buffer) {
  73654. buffer._rebuild();
  73655. }
  73656. var scene = this._source.getScene();
  73657. var engine = scene.getEngine();
  73658. this._ib = engine.createIndexBuffer(this._linesIndices);
  73659. };
  73660. EdgesRenderer.prototype.dispose = function () {
  73661. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73662. if (buffer) {
  73663. buffer.dispose();
  73664. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  73665. }
  73666. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73667. if (buffer) {
  73668. buffer.dispose();
  73669. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  73670. }
  73671. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  73672. this._lineShader.dispose();
  73673. };
  73674. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  73675. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  73676. return 0;
  73677. }
  73678. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  73679. return 1;
  73680. }
  73681. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  73682. return 2;
  73683. }
  73684. return -1;
  73685. };
  73686. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  73687. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  73688. return 0;
  73689. }
  73690. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  73691. return 1;
  73692. }
  73693. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  73694. return 2;
  73695. }
  73696. return -1;
  73697. };
  73698. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  73699. var needToCreateLine;
  73700. if (edge === undefined) {
  73701. needToCreateLine = true;
  73702. }
  73703. else {
  73704. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  73705. needToCreateLine = dotProduct < this._epsilon;
  73706. }
  73707. if (needToCreateLine) {
  73708. var offset = this._linesPositions.length / 3;
  73709. var normal = p0.subtract(p1);
  73710. normal.normalize();
  73711. // Positions
  73712. this._linesPositions.push(p0.x);
  73713. this._linesPositions.push(p0.y);
  73714. this._linesPositions.push(p0.z);
  73715. this._linesPositions.push(p0.x);
  73716. this._linesPositions.push(p0.y);
  73717. this._linesPositions.push(p0.z);
  73718. this._linesPositions.push(p1.x);
  73719. this._linesPositions.push(p1.y);
  73720. this._linesPositions.push(p1.z);
  73721. this._linesPositions.push(p1.x);
  73722. this._linesPositions.push(p1.y);
  73723. this._linesPositions.push(p1.z);
  73724. // Normals
  73725. this._linesNormals.push(p1.x);
  73726. this._linesNormals.push(p1.y);
  73727. this._linesNormals.push(p1.z);
  73728. this._linesNormals.push(-1);
  73729. this._linesNormals.push(p1.x);
  73730. this._linesNormals.push(p1.y);
  73731. this._linesNormals.push(p1.z);
  73732. this._linesNormals.push(1);
  73733. this._linesNormals.push(p0.x);
  73734. this._linesNormals.push(p0.y);
  73735. this._linesNormals.push(p0.z);
  73736. this._linesNormals.push(-1);
  73737. this._linesNormals.push(p0.x);
  73738. this._linesNormals.push(p0.y);
  73739. this._linesNormals.push(p0.z);
  73740. this._linesNormals.push(1);
  73741. // Indices
  73742. this._linesIndices.push(offset);
  73743. this._linesIndices.push(offset + 1);
  73744. this._linesIndices.push(offset + 2);
  73745. this._linesIndices.push(offset);
  73746. this._linesIndices.push(offset + 2);
  73747. this._linesIndices.push(offset + 3);
  73748. }
  73749. };
  73750. EdgesRenderer.prototype._generateEdgesLines = function () {
  73751. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73752. var indices = this._source.getIndices();
  73753. if (!indices || !positions) {
  73754. return;
  73755. }
  73756. // First let's find adjacencies
  73757. var adjacencies = new Array();
  73758. var faceNormals = new Array();
  73759. var index;
  73760. var faceAdjacencies;
  73761. // Prepare faces
  73762. for (index = 0; index < indices.length; index += 3) {
  73763. faceAdjacencies = new FaceAdjacencies();
  73764. var p0Index = indices[index];
  73765. var p1Index = indices[index + 1];
  73766. var p2Index = indices[index + 2];
  73767. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  73768. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  73769. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  73770. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  73771. faceNormal.normalize();
  73772. faceNormals.push(faceNormal);
  73773. adjacencies.push(faceAdjacencies);
  73774. }
  73775. // Scan
  73776. for (index = 0; index < adjacencies.length; index++) {
  73777. faceAdjacencies = adjacencies[index];
  73778. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  73779. var otherFaceAdjacencies = adjacencies[otherIndex];
  73780. if (faceAdjacencies.edgesConnectedCount === 3) {
  73781. break;
  73782. }
  73783. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  73784. continue;
  73785. }
  73786. var otherP0 = indices[otherIndex * 3];
  73787. var otherP1 = indices[otherIndex * 3 + 1];
  73788. var otherP2 = indices[otherIndex * 3 + 2];
  73789. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  73790. var otherEdgeIndex = 0;
  73791. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  73792. continue;
  73793. }
  73794. switch (edgeIndex) {
  73795. case 0:
  73796. if (this._checkVerticesInsteadOfIndices) {
  73797. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73798. }
  73799. else {
  73800. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  73801. }
  73802. break;
  73803. case 1:
  73804. if (this._checkVerticesInsteadOfIndices) {
  73805. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73806. }
  73807. else {
  73808. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  73809. }
  73810. break;
  73811. case 2:
  73812. if (this._checkVerticesInsteadOfIndices) {
  73813. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  73814. }
  73815. else {
  73816. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  73817. }
  73818. break;
  73819. }
  73820. if (otherEdgeIndex === -1) {
  73821. continue;
  73822. }
  73823. faceAdjacencies.edges[edgeIndex] = otherIndex;
  73824. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  73825. faceAdjacencies.edgesConnectedCount++;
  73826. otherFaceAdjacencies.edgesConnectedCount++;
  73827. if (faceAdjacencies.edgesConnectedCount === 3) {
  73828. break;
  73829. }
  73830. }
  73831. }
  73832. }
  73833. // Create lines
  73834. for (index = 0; index < adjacencies.length; index++) {
  73835. // 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
  73836. var current = adjacencies[index];
  73837. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  73838. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  73839. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  73840. }
  73841. // Merge into a single mesh
  73842. var engine = this._source.getScene().getEngine();
  73843. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  73844. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  73845. this._ib = engine.createIndexBuffer(this._linesIndices);
  73846. this._indicesCount = this._linesIndices.length;
  73847. };
  73848. EdgesRenderer.prototype.render = function () {
  73849. var scene = this._source.getScene();
  73850. if (!this._lineShader.isReady() || !scene.activeCamera) {
  73851. return;
  73852. }
  73853. var engine = scene.getEngine();
  73854. this._lineShader._preBind();
  73855. // VBOs
  73856. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  73857. scene.resetCachedMaterial();
  73858. this._lineShader.setColor4("color", this._source.edgesColor);
  73859. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  73860. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  73861. }
  73862. else {
  73863. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  73864. }
  73865. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  73866. this._lineShader.bind(this._source.getWorldMatrix());
  73867. // Draw order
  73868. engine.draw(true, 0, this._indicesCount);
  73869. this._lineShader.unbind();
  73870. engine.setDepthWrite(true);
  73871. };
  73872. return EdgesRenderer;
  73873. }());
  73874. BABYLON.EdgesRenderer = EdgesRenderer;
  73875. })(BABYLON || (BABYLON = {}));
  73876. //# sourceMappingURL=babylon.edgesRenderer.js.map
  73877. var BABYLON;
  73878. (function (BABYLON) {
  73879. /**
  73880. * Special Glow Blur post process only blurring the alpha channel
  73881. * It enforces keeping the most luminous color in the color channel.
  73882. */
  73883. var GlowBlurPostProcess = /** @class */ (function (_super) {
  73884. __extends(GlowBlurPostProcess, _super);
  73885. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  73886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73887. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  73888. _this.direction = direction;
  73889. _this.kernel = kernel;
  73890. _this.onApplyObservable.add(function (effect) {
  73891. effect.setFloat2("screenSize", _this.width, _this.height);
  73892. effect.setVector2("direction", _this.direction);
  73893. effect.setFloat("blurWidth", _this.kernel);
  73894. });
  73895. return _this;
  73896. }
  73897. return GlowBlurPostProcess;
  73898. }(BABYLON.PostProcess));
  73899. /**
  73900. * The highlight layer Helps adding a glow effect around a mesh.
  73901. *
  73902. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  73903. * glowy meshes to your scene.
  73904. *
  73905. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  73906. */
  73907. var HighlightLayer = /** @class */ (function () {
  73908. /**
  73909. * Instantiates a new highlight Layer and references it to the scene..
  73910. * @param name The name of the layer
  73911. * @param scene The scene to use the layer in
  73912. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  73913. */
  73914. function HighlightLayer(name, scene, options) {
  73915. this.name = name;
  73916. this._vertexBuffers = {};
  73917. this._mainTextureDesiredSize = { width: 0, height: 0 };
  73918. this._meshes = {};
  73919. this._maxSize = 0;
  73920. this._shouldRender = false;
  73921. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  73922. this._excludedMeshes = {};
  73923. /**
  73924. * Specifies whether or not the inner glow is ACTIVE in the layer.
  73925. */
  73926. this.innerGlow = true;
  73927. /**
  73928. * Specifies whether or not the outer glow is ACTIVE in the layer.
  73929. */
  73930. this.outerGlow = true;
  73931. /**
  73932. * Specifies wether the highlight layer is enabled or not.
  73933. */
  73934. this.isEnabled = true;
  73935. /**
  73936. * An event triggered when the highlight layer has been disposed.
  73937. * @type {BABYLON.Observable}
  73938. */
  73939. this.onDisposeObservable = new BABYLON.Observable();
  73940. /**
  73941. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  73942. * @type {BABYLON.Observable}
  73943. */
  73944. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  73945. /**
  73946. * An event triggered when the highlight layer is being blurred.
  73947. * @type {BABYLON.Observable}
  73948. */
  73949. this.onBeforeBlurObservable = new BABYLON.Observable();
  73950. /**
  73951. * An event triggered when the highlight layer has been blurred.
  73952. * @type {BABYLON.Observable}
  73953. */
  73954. this.onAfterBlurObservable = new BABYLON.Observable();
  73955. /**
  73956. * An event triggered when the glowing blurred texture is being merged in the scene.
  73957. * @type {BABYLON.Observable}
  73958. */
  73959. this.onBeforeComposeObservable = new BABYLON.Observable();
  73960. /**
  73961. * An event triggered when the glowing blurred texture has been merged in the scene.
  73962. * @type {BABYLON.Observable}
  73963. */
  73964. this.onAfterComposeObservable = new BABYLON.Observable();
  73965. /**
  73966. * An event triggered when the highlight layer changes its size.
  73967. * @type {BABYLON.Observable}
  73968. */
  73969. this.onSizeChangedObservable = new BABYLON.Observable();
  73970. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73971. var engine = scene.getEngine();
  73972. this._engine = engine;
  73973. this._maxSize = this._engine.getCaps().maxTextureSize;
  73974. this._scene.highlightLayers.push(this);
  73975. // Warn on stencil.
  73976. if (!this._engine.isStencilEnable) {
  73977. 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 }");
  73978. }
  73979. // Adapt options
  73980. this._options = options || {
  73981. mainTextureRatio: 0.5,
  73982. blurTextureSizeRatio: 0.5,
  73983. blurHorizontalSize: 1.0,
  73984. blurVerticalSize: 1.0,
  73985. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  73986. camera: null
  73987. };
  73988. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  73989. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  73990. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  73991. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  73992. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  73993. // VBO
  73994. var vertices = [];
  73995. vertices.push(1, 1);
  73996. vertices.push(-1, 1);
  73997. vertices.push(-1, -1);
  73998. vertices.push(1, -1);
  73999. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74001. this._createIndexBuffer();
  74002. // Effect
  74003. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  74004. // Render target
  74005. this.setMainTextureSize();
  74006. // Create Textures and post processes
  74007. this.createTextureAndPostProcesses();
  74008. }
  74009. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  74010. /**
  74011. * Gets the horizontal size of the blur.
  74012. */
  74013. get: function () {
  74014. return this._horizontalBlurPostprocess.kernel;
  74015. },
  74016. /**
  74017. * Specifies the horizontal size of the blur.
  74018. */
  74019. set: function (value) {
  74020. this._horizontalBlurPostprocess.kernel = value;
  74021. },
  74022. enumerable: true,
  74023. configurable: true
  74024. });
  74025. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  74026. /**
  74027. * Gets the vertical size of the blur.
  74028. */
  74029. get: function () {
  74030. return this._verticalBlurPostprocess.kernel;
  74031. },
  74032. /**
  74033. * Specifies the vertical size of the blur.
  74034. */
  74035. set: function (value) {
  74036. this._verticalBlurPostprocess.kernel = value;
  74037. },
  74038. enumerable: true,
  74039. configurable: true
  74040. });
  74041. Object.defineProperty(HighlightLayer.prototype, "camera", {
  74042. /**
  74043. * Gets the camera attached to the layer.
  74044. */
  74045. get: function () {
  74046. return this._options.camera;
  74047. },
  74048. enumerable: true,
  74049. configurable: true
  74050. });
  74051. HighlightLayer.prototype._createIndexBuffer = function () {
  74052. var engine = this._scene.getEngine();
  74053. // Indices
  74054. var indices = [];
  74055. indices.push(0);
  74056. indices.push(1);
  74057. indices.push(2);
  74058. indices.push(0);
  74059. indices.push(2);
  74060. indices.push(3);
  74061. this._indexBuffer = engine.createIndexBuffer(indices);
  74062. };
  74063. HighlightLayer.prototype._rebuild = function () {
  74064. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74065. if (vb) {
  74066. vb._rebuild();
  74067. }
  74068. this._createIndexBuffer();
  74069. };
  74070. /**
  74071. * Creates the render target textures and post processes used in the highlight layer.
  74072. */
  74073. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  74074. var _this = this;
  74075. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  74076. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  74077. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  74078. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  74079. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  74080. width: this._mainTextureDesiredSize.width,
  74081. height: this._mainTextureDesiredSize.height
  74082. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74083. this._mainTexture.activeCamera = this._options.camera;
  74084. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74085. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74086. this._mainTexture.anisotropicFilteringLevel = 1;
  74087. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74088. this._mainTexture.renderParticles = false;
  74089. this._mainTexture.renderList = null;
  74090. this._mainTexture.ignoreCameraViewport = true;
  74091. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  74092. width: blurTextureWidth,
  74093. height: blurTextureHeight
  74094. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74095. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74096. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74097. this._blurTexture.anisotropicFilteringLevel = 16;
  74098. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74099. this._blurTexture.renderParticles = false;
  74100. this._blurTexture.ignoreCameraViewport = true;
  74101. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74102. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  74103. effect.setTexture("textureSampler", _this._mainTexture);
  74104. });
  74105. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  74106. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74107. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74108. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74109. });
  74110. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74111. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74112. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74113. });
  74114. }
  74115. else {
  74116. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74117. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74118. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74119. });
  74120. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74121. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74122. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74123. });
  74124. }
  74125. this._mainTexture.onAfterUnbindObservable.add(function () {
  74126. _this.onBeforeBlurObservable.notifyObservers(_this);
  74127. var internalTexture = _this._blurTexture.getInternalTexture();
  74128. if (internalTexture) {
  74129. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  74130. }
  74131. _this.onAfterBlurObservable.notifyObservers(_this);
  74132. });
  74133. // Custom render function
  74134. var renderSubMesh = function (subMesh) {
  74135. if (!_this._meshes) {
  74136. return;
  74137. }
  74138. var material = subMesh.getMaterial();
  74139. var mesh = subMesh.getRenderingMesh();
  74140. var scene = _this._scene;
  74141. var engine = scene.getEngine();
  74142. if (!material) {
  74143. return;
  74144. }
  74145. // Do not block in blend mode.
  74146. if (material.needAlphaBlendingForMesh(mesh)) {
  74147. return;
  74148. }
  74149. // Culling
  74150. engine.setState(material.backFaceCulling);
  74151. // Managing instances
  74152. var batch = mesh._getInstancesRenderList(subMesh._id);
  74153. if (batch.mustReturn) {
  74154. return;
  74155. }
  74156. // Excluded Mesh
  74157. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74158. return;
  74159. }
  74160. ;
  74161. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74162. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  74163. var emissiveTexture = null;
  74164. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  74165. emissiveTexture = material.emissiveTexture;
  74166. }
  74167. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  74168. engine.enableEffect(_this._glowMapGenerationEffect);
  74169. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  74170. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  74171. if (highlightLayerMesh) {
  74172. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  74173. }
  74174. else {
  74175. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  74176. }
  74177. // Alpha test
  74178. if (material && material.needAlphaTesting()) {
  74179. var alphaTexture = material.getAlphaTestTexture();
  74180. if (alphaTexture) {
  74181. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  74182. var textureMatrix = alphaTexture.getTextureMatrix();
  74183. if (textureMatrix) {
  74184. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  74185. }
  74186. }
  74187. }
  74188. // Glow emissive only
  74189. if (emissiveTexture) {
  74190. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  74191. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  74192. }
  74193. // Bones
  74194. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74195. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74196. }
  74197. // Draw
  74198. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  74199. }
  74200. else {
  74201. // Need to reset refresh rate of the shadowMap
  74202. _this._mainTexture.resetRefreshCounter();
  74203. }
  74204. };
  74205. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74206. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  74207. var index;
  74208. var engine = _this._scene.getEngine();
  74209. if (depthOnlySubMeshes.length) {
  74210. engine.setColorWrite(false);
  74211. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74212. renderSubMesh(depthOnlySubMeshes.data[index]);
  74213. }
  74214. engine.setColorWrite(true);
  74215. }
  74216. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74217. renderSubMesh(opaqueSubMeshes.data[index]);
  74218. }
  74219. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74220. renderSubMesh(alphaTestSubMeshes.data[index]);
  74221. }
  74222. for (index = 0; index < transparentSubMeshes.length; index++) {
  74223. renderSubMesh(transparentSubMeshes.data[index]);
  74224. }
  74225. };
  74226. this._mainTexture.onClearObservable.add(function (engine) {
  74227. engine.clear(HighlightLayer.neutralColor, true, true, true);
  74228. });
  74229. };
  74230. /**
  74231. * Checks for the readiness of the element composing the layer.
  74232. * @param subMesh the mesh to check for
  74233. * @param useInstances specify wether or not to use instances to render the mesh
  74234. * @param emissiveTexture the associated emissive texture used to generate the glow
  74235. * @return true if ready otherwise, false
  74236. */
  74237. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  74238. var material = subMesh.getMaterial();
  74239. if (!material) {
  74240. return false;
  74241. }
  74242. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  74243. return false;
  74244. }
  74245. var defines = [];
  74246. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74247. var mesh = subMesh.getMesh();
  74248. var uv1 = false;
  74249. var uv2 = false;
  74250. // Alpha test
  74251. if (material && material.needAlphaTesting()) {
  74252. var alphaTexture = material.getAlphaTestTexture();
  74253. if (alphaTexture) {
  74254. defines.push("#define ALPHATEST");
  74255. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74256. alphaTexture.coordinatesIndex === 1) {
  74257. defines.push("#define DIFFUSEUV2");
  74258. uv2 = true;
  74259. }
  74260. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74261. defines.push("#define DIFFUSEUV1");
  74262. uv1 = true;
  74263. }
  74264. }
  74265. }
  74266. // Emissive
  74267. if (emissiveTexture) {
  74268. defines.push("#define EMISSIVE");
  74269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74270. emissiveTexture.coordinatesIndex === 1) {
  74271. defines.push("#define EMISSIVEUV2");
  74272. uv2 = true;
  74273. }
  74274. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74275. defines.push("#define EMISSIVEUV1");
  74276. uv1 = true;
  74277. }
  74278. }
  74279. if (uv1) {
  74280. attribs.push(BABYLON.VertexBuffer.UVKind);
  74281. defines.push("#define UV1");
  74282. }
  74283. if (uv2) {
  74284. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74285. defines.push("#define UV2");
  74286. }
  74287. // Bones
  74288. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74289. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74290. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74291. if (mesh.numBoneInfluencers > 4) {
  74292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74294. }
  74295. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74296. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74297. }
  74298. else {
  74299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74300. }
  74301. // Instances
  74302. if (useInstances) {
  74303. defines.push("#define INSTANCES");
  74304. attribs.push("world0");
  74305. attribs.push("world1");
  74306. attribs.push("world2");
  74307. attribs.push("world3");
  74308. }
  74309. // Get correct effect
  74310. var join = defines.join("\n");
  74311. if (this._cachedDefines !== join) {
  74312. this._cachedDefines = join;
  74313. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  74314. }
  74315. return this._glowMapGenerationEffect.isReady();
  74316. };
  74317. /**
  74318. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  74319. */
  74320. HighlightLayer.prototype.render = function () {
  74321. var currentEffect = this._glowMapMergeEffect;
  74322. // Check
  74323. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  74324. return;
  74325. var engine = this._scene.getEngine();
  74326. this.onBeforeComposeObservable.notifyObservers(this);
  74327. // Render
  74328. engine.enableEffect(currentEffect);
  74329. engine.setState(false);
  74330. // Cache
  74331. var previousStencilBuffer = engine.getStencilBuffer();
  74332. var previousStencilFunction = engine.getStencilFunction();
  74333. var previousStencilMask = engine.getStencilMask();
  74334. var previousStencilOperationPass = engine.getStencilOperationPass();
  74335. var previousStencilOperationFail = engine.getStencilOperationFail();
  74336. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  74337. var previousAlphaMode = engine.getAlphaMode();
  74338. // Texture
  74339. currentEffect.setTexture("textureSampler", this._blurTexture);
  74340. // VBOs
  74341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  74342. // Stencil operations
  74343. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  74344. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  74345. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  74346. // Draw order
  74347. engine.setAlphaMode(this._options.alphaBlendingMode);
  74348. engine.setStencilMask(0x00);
  74349. engine.setStencilBuffer(true);
  74350. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  74351. if (this.outerGlow) {
  74352. currentEffect.setFloat("offset", 0);
  74353. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  74354. engine.draw(true, 0, 6);
  74355. }
  74356. if (this.innerGlow) {
  74357. currentEffect.setFloat("offset", 1);
  74358. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  74359. engine.draw(true, 0, 6);
  74360. }
  74361. // Restore Cache
  74362. engine.setStencilFunction(previousStencilFunction);
  74363. engine.setStencilMask(previousStencilMask);
  74364. engine.setAlphaMode(previousAlphaMode);
  74365. engine.setStencilBuffer(previousStencilBuffer);
  74366. engine.setStencilOperationPass(previousStencilOperationPass);
  74367. engine.setStencilOperationFail(previousStencilOperationFail);
  74368. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  74369. engine._stencilState.reset();
  74370. this.onAfterComposeObservable.notifyObservers(this);
  74371. // Handle size changes.
  74372. var size = this._mainTexture.getSize();
  74373. this.setMainTextureSize();
  74374. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  74375. // Recreate RTT and post processes on size change.
  74376. this.onSizeChangedObservable.notifyObservers(this);
  74377. this.disposeTextureAndPostProcesses();
  74378. this.createTextureAndPostProcesses();
  74379. }
  74380. };
  74381. /**
  74382. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  74383. * @param mesh The mesh to exclude from the highlight layer
  74384. */
  74385. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  74386. if (!this._excludedMeshes) {
  74387. return;
  74388. }
  74389. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74390. if (!meshExcluded) {
  74391. this._excludedMeshes[mesh.uniqueId] = {
  74392. mesh: mesh,
  74393. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  74394. mesh.getEngine().setStencilBuffer(false);
  74395. }),
  74396. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  74397. mesh.getEngine().setStencilBuffer(true);
  74398. }),
  74399. };
  74400. }
  74401. };
  74402. /**
  74403. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  74404. * @param mesh The mesh to highlight
  74405. */
  74406. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  74407. if (!this._excludedMeshes) {
  74408. return;
  74409. }
  74410. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74411. if (meshExcluded) {
  74412. if (meshExcluded.beforeRender) {
  74413. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  74414. }
  74415. if (meshExcluded.afterRender) {
  74416. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  74417. }
  74418. }
  74419. this._excludedMeshes[mesh.uniqueId] = null;
  74420. };
  74421. /**
  74422. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  74423. * @param mesh The mesh to highlight
  74424. * @param color The color of the highlight
  74425. * @param glowEmissiveOnly Extract the glow from the emissive texture
  74426. */
  74427. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  74428. var _this = this;
  74429. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  74430. if (!this._meshes) {
  74431. return;
  74432. }
  74433. var meshHighlight = this._meshes[mesh.uniqueId];
  74434. if (meshHighlight) {
  74435. meshHighlight.color = color;
  74436. }
  74437. else {
  74438. this._meshes[mesh.uniqueId] = {
  74439. mesh: mesh,
  74440. color: color,
  74441. // Lambda required for capture due to Observable this context
  74442. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  74443. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74444. _this.defaultStencilReference(mesh);
  74445. }
  74446. else {
  74447. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  74448. }
  74449. }),
  74450. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  74451. glowEmissiveOnly: glowEmissiveOnly
  74452. };
  74453. }
  74454. this._shouldRender = true;
  74455. };
  74456. /**
  74457. * Remove a mesh from the highlight layer in order to make it stop glowing.
  74458. * @param mesh The mesh to highlight
  74459. */
  74460. HighlightLayer.prototype.removeMesh = function (mesh) {
  74461. if (!this._meshes) {
  74462. return;
  74463. }
  74464. var meshHighlight = this._meshes[mesh.uniqueId];
  74465. if (meshHighlight) {
  74466. if (meshHighlight.observerHighlight) {
  74467. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74468. }
  74469. if (meshHighlight.observerDefault) {
  74470. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74471. }
  74472. }
  74473. this._meshes[mesh.uniqueId] = null;
  74474. this._shouldRender = false;
  74475. for (var meshHighlightToCheck in this._meshes) {
  74476. if (this._meshes[meshHighlightToCheck]) {
  74477. this._shouldRender = true;
  74478. break;
  74479. }
  74480. }
  74481. };
  74482. /**
  74483. * Returns true if the layer contains information to display, otherwise false.
  74484. */
  74485. HighlightLayer.prototype.shouldRender = function () {
  74486. return this.isEnabled && this._shouldRender;
  74487. };
  74488. /**
  74489. * Sets the main texture desired size which is the closest power of two
  74490. * of the engine canvas size.
  74491. */
  74492. HighlightLayer.prototype.setMainTextureSize = function () {
  74493. if (this._options.mainTextureFixedSize) {
  74494. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  74495. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  74496. }
  74497. else {
  74498. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  74499. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  74500. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  74501. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  74502. }
  74503. };
  74504. /**
  74505. * Force the stencil to the normal expected value for none glowing parts
  74506. */
  74507. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  74508. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  74509. };
  74510. /**
  74511. * Dispose only the render target textures and post process.
  74512. */
  74513. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  74514. this._blurTexture.dispose();
  74515. this._mainTexture.dispose();
  74516. this._downSamplePostprocess.dispose();
  74517. this._horizontalBlurPostprocess.dispose();
  74518. this._verticalBlurPostprocess.dispose();
  74519. };
  74520. /**
  74521. * Dispose the highlight layer and free resources.
  74522. */
  74523. HighlightLayer.prototype.dispose = function () {
  74524. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74525. if (vertexBuffer) {
  74526. vertexBuffer.dispose();
  74527. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74528. }
  74529. if (this._indexBuffer) {
  74530. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74531. this._indexBuffer = null;
  74532. }
  74533. // Clean textures and post processes
  74534. this.disposeTextureAndPostProcesses();
  74535. if (this._meshes) {
  74536. // Clean mesh references
  74537. for (var id in this._meshes) {
  74538. var meshHighlight = this._meshes[id];
  74539. if (meshHighlight && meshHighlight.mesh) {
  74540. if (meshHighlight.observerHighlight) {
  74541. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74542. }
  74543. if (meshHighlight.observerDefault) {
  74544. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74545. }
  74546. }
  74547. }
  74548. this._meshes = null;
  74549. }
  74550. if (this._excludedMeshes) {
  74551. for (var id in this._excludedMeshes) {
  74552. var meshHighlight = this._excludedMeshes[id];
  74553. if (meshHighlight) {
  74554. if (meshHighlight.beforeRender) {
  74555. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  74556. }
  74557. if (meshHighlight.afterRender) {
  74558. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  74559. }
  74560. }
  74561. }
  74562. this._excludedMeshes = null;
  74563. }
  74564. // Remove from scene
  74565. var index = this._scene.highlightLayers.indexOf(this, 0);
  74566. if (index > -1) {
  74567. this._scene.highlightLayers.splice(index, 1);
  74568. }
  74569. // Callback
  74570. this.onDisposeObservable.notifyObservers(this);
  74571. this.onDisposeObservable.clear();
  74572. this.onBeforeRenderMainTextureObservable.clear();
  74573. this.onBeforeBlurObservable.clear();
  74574. this.onBeforeComposeObservable.clear();
  74575. this.onAfterComposeObservable.clear();
  74576. this.onSizeChangedObservable.clear();
  74577. };
  74578. /**
  74579. * The neutral color used during the preparation of the glow effect.
  74580. * This is black by default as the blend operation is a blend operation.
  74581. */
  74582. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  74583. /**
  74584. * Stencil value used for glowing meshes.
  74585. */
  74586. HighlightLayer.glowingMeshStencilReference = 0x02;
  74587. /**
  74588. * Stencil value used for the other meshes in the scene.
  74589. */
  74590. HighlightLayer.normalMeshStencilReference = 0x01;
  74591. return HighlightLayer;
  74592. }());
  74593. BABYLON.HighlightLayer = HighlightLayer;
  74594. })(BABYLON || (BABYLON = {}));
  74595. //# sourceMappingURL=babylon.highlightlayer.js.map
  74596. var BABYLON;
  74597. (function (BABYLON) {
  74598. var AssetTaskState;
  74599. (function (AssetTaskState) {
  74600. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  74601. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  74602. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  74603. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  74604. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  74605. var AbstractAssetTask = /** @class */ (function () {
  74606. function AbstractAssetTask(name) {
  74607. this.name = name;
  74608. this.isCompleted = false;
  74609. this.taskState = AssetTaskState.INIT;
  74610. }
  74611. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74612. var _this = this;
  74613. this.taskState = AssetTaskState.RUNNING;
  74614. this.runTask(scene, function () {
  74615. _this.onDoneCallback(onSuccess, onError);
  74616. }, function (msg, exception) {
  74617. _this.onErrorCallback(onError, msg, exception);
  74618. });
  74619. };
  74620. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74621. throw new Error("runTask is not implemented");
  74622. };
  74623. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  74624. this.taskState = AssetTaskState.ERROR;
  74625. this.errorObject = {
  74626. message: message,
  74627. exception: exception
  74628. };
  74629. if (this.onError) {
  74630. this.onError(this, message, exception);
  74631. }
  74632. onError();
  74633. };
  74634. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  74635. try {
  74636. this.taskState = AssetTaskState.DONE;
  74637. this.isCompleted = true;
  74638. if (this.onSuccess) {
  74639. this.onSuccess(this);
  74640. }
  74641. onSuccess();
  74642. }
  74643. catch (e) {
  74644. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  74645. }
  74646. };
  74647. return AbstractAssetTask;
  74648. }());
  74649. BABYLON.AbstractAssetTask = AbstractAssetTask;
  74650. var AssetsProgressEvent = /** @class */ (function () {
  74651. function AssetsProgressEvent(remainingCount, totalCount, task) {
  74652. this.remainingCount = remainingCount;
  74653. this.totalCount = totalCount;
  74654. this.task = task;
  74655. }
  74656. return AssetsProgressEvent;
  74657. }());
  74658. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  74659. var MeshAssetTask = /** @class */ (function (_super) {
  74660. __extends(MeshAssetTask, _super);
  74661. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  74662. var _this = _super.call(this, name) || this;
  74663. _this.name = name;
  74664. _this.meshesNames = meshesNames;
  74665. _this.rootUrl = rootUrl;
  74666. _this.sceneFilename = sceneFilename;
  74667. return _this;
  74668. }
  74669. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74670. var _this = this;
  74671. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  74672. _this.loadedMeshes = meshes;
  74673. _this.loadedParticleSystems = particleSystems;
  74674. _this.loadedSkeletons = skeletons;
  74675. onSuccess();
  74676. }, null, function (scene, message, exception) {
  74677. onError(message, exception);
  74678. });
  74679. };
  74680. return MeshAssetTask;
  74681. }(AbstractAssetTask));
  74682. BABYLON.MeshAssetTask = MeshAssetTask;
  74683. var TextFileAssetTask = /** @class */ (function (_super) {
  74684. __extends(TextFileAssetTask, _super);
  74685. function TextFileAssetTask(name, url) {
  74686. var _this = _super.call(this, name) || this;
  74687. _this.name = name;
  74688. _this.url = url;
  74689. return _this;
  74690. }
  74691. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74692. var _this = this;
  74693. BABYLON.Tools.LoadFile(this.url, function (data) {
  74694. _this.text = data;
  74695. onSuccess();
  74696. }, undefined, scene.database, false, function (request, exception) {
  74697. if (request) {
  74698. onError(request.status + " " + request.statusText, exception);
  74699. }
  74700. });
  74701. };
  74702. return TextFileAssetTask;
  74703. }(AbstractAssetTask));
  74704. BABYLON.TextFileAssetTask = TextFileAssetTask;
  74705. var BinaryFileAssetTask = /** @class */ (function (_super) {
  74706. __extends(BinaryFileAssetTask, _super);
  74707. function BinaryFileAssetTask(name, url) {
  74708. var _this = _super.call(this, name) || this;
  74709. _this.name = name;
  74710. _this.url = url;
  74711. return _this;
  74712. }
  74713. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74714. var _this = this;
  74715. BABYLON.Tools.LoadFile(this.url, function (data) {
  74716. _this.data = data;
  74717. onSuccess();
  74718. }, undefined, scene.database, true, function (request, exception) {
  74719. if (request) {
  74720. onError(request.status + " " + request.statusText, exception);
  74721. }
  74722. });
  74723. };
  74724. return BinaryFileAssetTask;
  74725. }(AbstractAssetTask));
  74726. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  74727. var ImageAssetTask = /** @class */ (function (_super) {
  74728. __extends(ImageAssetTask, _super);
  74729. function ImageAssetTask(name, url) {
  74730. var _this = _super.call(this, name) || this;
  74731. _this.name = name;
  74732. _this.url = url;
  74733. return _this;
  74734. }
  74735. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74736. var _this = this;
  74737. var img = new Image();
  74738. BABYLON.Tools.SetCorsBehavior(this.url, img);
  74739. img.onload = function () {
  74740. _this.image = img;
  74741. onSuccess();
  74742. };
  74743. img.onerror = function (err) {
  74744. onError("Error loading image", err);
  74745. };
  74746. img.src = this.url;
  74747. };
  74748. return ImageAssetTask;
  74749. }(AbstractAssetTask));
  74750. BABYLON.ImageAssetTask = ImageAssetTask;
  74751. var TextureAssetTask = /** @class */ (function (_super) {
  74752. __extends(TextureAssetTask, _super);
  74753. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  74754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74755. var _this = _super.call(this, name) || this;
  74756. _this.name = name;
  74757. _this.url = url;
  74758. _this.noMipmap = noMipmap;
  74759. _this.invertY = invertY;
  74760. _this.samplingMode = samplingMode;
  74761. return _this;
  74762. }
  74763. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74764. var onload = function () {
  74765. onSuccess();
  74766. };
  74767. var onerror = function (message, exception) {
  74768. onError(message, exception);
  74769. };
  74770. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  74771. };
  74772. return TextureAssetTask;
  74773. }(AbstractAssetTask));
  74774. BABYLON.TextureAssetTask = TextureAssetTask;
  74775. var CubeTextureAssetTask = /** @class */ (function (_super) {
  74776. __extends(CubeTextureAssetTask, _super);
  74777. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  74778. var _this = _super.call(this, name) || this;
  74779. _this.name = name;
  74780. _this.url = url;
  74781. _this.extensions = extensions;
  74782. _this.noMipmap = noMipmap;
  74783. _this.files = files;
  74784. return _this;
  74785. }
  74786. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74787. var onload = function () {
  74788. onSuccess();
  74789. };
  74790. var onerror = function (message, exception) {
  74791. onError(message, exception);
  74792. };
  74793. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  74794. };
  74795. return CubeTextureAssetTask;
  74796. }(AbstractAssetTask));
  74797. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  74798. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  74799. __extends(HDRCubeTextureAssetTask, _super);
  74800. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74801. if (noMipmap === void 0) { noMipmap = false; }
  74802. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74803. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74804. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74805. var _this = _super.call(this, name) || this;
  74806. _this.name = name;
  74807. _this.url = url;
  74808. _this.size = size;
  74809. _this.noMipmap = noMipmap;
  74810. _this.generateHarmonics = generateHarmonics;
  74811. _this.useInGammaSpace = useInGammaSpace;
  74812. _this.usePMREMGenerator = usePMREMGenerator;
  74813. return _this;
  74814. }
  74815. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74816. var onload = function () {
  74817. onSuccess();
  74818. };
  74819. var onerror = function (message, exception) {
  74820. onError(message, exception);
  74821. };
  74822. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  74823. };
  74824. return HDRCubeTextureAssetTask;
  74825. }(AbstractAssetTask));
  74826. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  74827. var AssetsManager = /** @class */ (function () {
  74828. function AssetsManager(scene) {
  74829. this.tasks = new Array();
  74830. this.waitingTasksCount = 0;
  74831. //Observables
  74832. this.onTaskSuccessObservable = new BABYLON.Observable();
  74833. this.onTaskErrorObservable = new BABYLON.Observable();
  74834. this.onTasksDoneObservable = new BABYLON.Observable();
  74835. this.onProgressObservable = new BABYLON.Observable();
  74836. this.useDefaultLoadingScreen = true;
  74837. this._scene = scene;
  74838. }
  74839. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  74840. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  74841. this.tasks.push(task);
  74842. return task;
  74843. };
  74844. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  74845. var task = new TextFileAssetTask(taskName, url);
  74846. this.tasks.push(task);
  74847. return task;
  74848. };
  74849. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  74850. var task = new BinaryFileAssetTask(taskName, url);
  74851. this.tasks.push(task);
  74852. return task;
  74853. };
  74854. AssetsManager.prototype.addImageTask = function (taskName, url) {
  74855. var task = new ImageAssetTask(taskName, url);
  74856. this.tasks.push(task);
  74857. return task;
  74858. };
  74859. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  74860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74861. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  74862. this.tasks.push(task);
  74863. return task;
  74864. };
  74865. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  74866. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  74867. this.tasks.push(task);
  74868. return task;
  74869. };
  74870. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  74871. if (noMipmap === void 0) { noMipmap = false; }
  74872. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74873. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74874. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74875. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  74876. this.tasks.push(task);
  74877. return task;
  74878. };
  74879. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  74880. this.waitingTasksCount--;
  74881. try {
  74882. if (this.onProgress) {
  74883. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  74884. }
  74885. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  74886. }
  74887. catch (e) {
  74888. BABYLON.Tools.Error("Error running progress callbacks.");
  74889. console.log(e);
  74890. }
  74891. if (this.waitingTasksCount === 0) {
  74892. try {
  74893. if (this.onFinish) {
  74894. this.onFinish(this.tasks);
  74895. }
  74896. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74897. }
  74898. catch (e) {
  74899. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  74900. console.log(e);
  74901. }
  74902. this._scene.getEngine().hideLoadingUI();
  74903. }
  74904. };
  74905. AssetsManager.prototype._runTask = function (task) {
  74906. var _this = this;
  74907. var done = function () {
  74908. try {
  74909. if (_this.onTaskSuccess) {
  74910. _this.onTaskSuccess(task);
  74911. }
  74912. _this.onTaskSuccessObservable.notifyObservers(task);
  74913. _this._decreaseWaitingTasksCount(task);
  74914. }
  74915. catch (e) {
  74916. error("Error executing task success callbacks", e);
  74917. }
  74918. };
  74919. var error = function (message, exception) {
  74920. task.errorObject = task.errorObject || {
  74921. message: message,
  74922. exception: exception
  74923. };
  74924. if (_this.onTaskError) {
  74925. _this.onTaskError(task);
  74926. }
  74927. _this.onTaskErrorObservable.notifyObservers(task);
  74928. _this._decreaseWaitingTasksCount(task);
  74929. };
  74930. task.run(this._scene, done, error);
  74931. };
  74932. AssetsManager.prototype.reset = function () {
  74933. this.tasks = new Array();
  74934. return this;
  74935. };
  74936. AssetsManager.prototype.load = function () {
  74937. this.waitingTasksCount = this.tasks.length;
  74938. if (this.waitingTasksCount === 0) {
  74939. if (this.onFinish) {
  74940. this.onFinish(this.tasks);
  74941. }
  74942. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74943. return this;
  74944. }
  74945. if (this.useDefaultLoadingScreen) {
  74946. this._scene.getEngine().displayLoadingUI();
  74947. }
  74948. for (var index = 0; index < this.tasks.length; index++) {
  74949. var task = this.tasks[index];
  74950. this._runTask(task);
  74951. }
  74952. return this;
  74953. };
  74954. return AssetsManager;
  74955. }());
  74956. BABYLON.AssetsManager = AssetsManager;
  74957. })(BABYLON || (BABYLON = {}));
  74958. //# sourceMappingURL=babylon.assetsManager.js.map
  74959. var BABYLON;
  74960. (function (BABYLON) {
  74961. var serializedGeometries = [];
  74962. var serializeGeometry = function (geometry, serializationGeometries) {
  74963. if (serializedGeometries[geometry.id]) {
  74964. return;
  74965. }
  74966. if (geometry.doNotSerialize) {
  74967. return;
  74968. }
  74969. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  74970. serializationGeometries.boxes.push(geometry.serialize());
  74971. }
  74972. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  74973. serializationGeometries.spheres.push(geometry.serialize());
  74974. }
  74975. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  74976. serializationGeometries.cylinders.push(geometry.serialize());
  74977. }
  74978. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  74979. serializationGeometries.toruses.push(geometry.serialize());
  74980. }
  74981. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  74982. serializationGeometries.grounds.push(geometry.serialize());
  74983. }
  74984. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  74985. serializationGeometries.planes.push(geometry.serialize());
  74986. }
  74987. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  74988. serializationGeometries.torusKnots.push(geometry.serialize());
  74989. }
  74990. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  74991. throw new Error("Unknown primitive type");
  74992. }
  74993. else {
  74994. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  74995. }
  74996. serializedGeometries[geometry.id] = true;
  74997. };
  74998. var serializeMesh = function (mesh, serializationScene) {
  74999. var serializationObject = {};
  75000. // Geometry
  75001. var geometry = mesh._geometry;
  75002. if (geometry) {
  75003. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  75004. // 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
  75005. serializeGeometry(geometry, serializationScene.geometries);
  75006. }
  75007. }
  75008. // Custom
  75009. if (mesh.serialize) {
  75010. mesh.serialize(serializationObject);
  75011. }
  75012. return serializationObject;
  75013. };
  75014. var finalizeSingleMesh = function (mesh, serializationObject) {
  75015. //only works if the mesh is already loaded
  75016. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75017. //serialize material
  75018. if (mesh.material) {
  75019. if (mesh.material instanceof BABYLON.StandardMaterial) {
  75020. serializationObject.materials = serializationObject.materials || [];
  75021. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75022. serializationObject.materials.push(mesh.material.serialize());
  75023. }
  75024. }
  75025. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  75026. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  75027. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75028. serializationObject.multiMaterials.push(mesh.material.serialize());
  75029. }
  75030. }
  75031. }
  75032. //serialize geometry
  75033. var geometry = mesh._geometry;
  75034. if (geometry) {
  75035. if (!serializationObject.geometries) {
  75036. serializationObject.geometries = {};
  75037. serializationObject.geometries.boxes = [];
  75038. serializationObject.geometries.spheres = [];
  75039. serializationObject.geometries.cylinders = [];
  75040. serializationObject.geometries.toruses = [];
  75041. serializationObject.geometries.grounds = [];
  75042. serializationObject.geometries.planes = [];
  75043. serializationObject.geometries.torusKnots = [];
  75044. serializationObject.geometries.vertexData = [];
  75045. }
  75046. serializeGeometry(geometry, serializationObject.geometries);
  75047. }
  75048. // Skeletons
  75049. if (mesh.skeleton) {
  75050. serializationObject.skeletons = serializationObject.skeletons || [];
  75051. serializationObject.skeletons.push(mesh.skeleton.serialize());
  75052. }
  75053. //serialize the actual mesh
  75054. serializationObject.meshes = serializationObject.meshes || [];
  75055. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75056. }
  75057. };
  75058. var SceneSerializer = /** @class */ (function () {
  75059. function SceneSerializer() {
  75060. }
  75061. SceneSerializer.ClearCache = function () {
  75062. serializedGeometries = [];
  75063. };
  75064. SceneSerializer.Serialize = function (scene) {
  75065. var serializationObject = {};
  75066. SceneSerializer.ClearCache();
  75067. // Scene
  75068. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  75069. serializationObject.autoClear = scene.autoClear;
  75070. serializationObject.clearColor = scene.clearColor.asArray();
  75071. serializationObject.ambientColor = scene.ambientColor.asArray();
  75072. serializationObject.gravity = scene.gravity.asArray();
  75073. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  75074. serializationObject.workerCollisions = scene.workerCollisions;
  75075. // Fog
  75076. if (scene.fogMode && scene.fogMode !== 0) {
  75077. serializationObject.fogMode = scene.fogMode;
  75078. serializationObject.fogColor = scene.fogColor.asArray();
  75079. serializationObject.fogStart = scene.fogStart;
  75080. serializationObject.fogEnd = scene.fogEnd;
  75081. serializationObject.fogDensity = scene.fogDensity;
  75082. }
  75083. //Physics
  75084. if (scene.isPhysicsEnabled()) {
  75085. var physicEngine = scene.getPhysicsEngine();
  75086. if (physicEngine) {
  75087. serializationObject.physicsEnabled = true;
  75088. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  75089. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  75090. }
  75091. }
  75092. // Metadata
  75093. if (scene.metadata) {
  75094. serializationObject.metadata = scene.metadata;
  75095. }
  75096. // Morph targets
  75097. serializationObject.morphTargetManagers = [];
  75098. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  75099. var abstractMesh = _a[_i];
  75100. var manager = abstractMesh.morphTargetManager;
  75101. if (manager) {
  75102. serializationObject.morphTargetManagers.push(manager.serialize());
  75103. }
  75104. }
  75105. // Lights
  75106. serializationObject.lights = [];
  75107. var index;
  75108. var light;
  75109. for (index = 0; index < scene.lights.length; index++) {
  75110. light = scene.lights[index];
  75111. if (!light.doNotSerialize) {
  75112. serializationObject.lights.push(light.serialize());
  75113. }
  75114. }
  75115. // Cameras
  75116. serializationObject.cameras = [];
  75117. for (index = 0; index < scene.cameras.length; index++) {
  75118. var camera = scene.cameras[index];
  75119. if (!camera.doNotSerialize) {
  75120. serializationObject.cameras.push(camera.serialize());
  75121. }
  75122. }
  75123. if (scene.activeCamera) {
  75124. serializationObject.activeCameraID = scene.activeCamera.id;
  75125. }
  75126. // Animations
  75127. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  75128. // Materials
  75129. serializationObject.materials = [];
  75130. serializationObject.multiMaterials = [];
  75131. var material;
  75132. for (index = 0; index < scene.materials.length; index++) {
  75133. material = scene.materials[index];
  75134. if (!material.doNotSerialize) {
  75135. serializationObject.materials.push(material.serialize());
  75136. }
  75137. }
  75138. // MultiMaterials
  75139. serializationObject.multiMaterials = [];
  75140. for (index = 0; index < scene.multiMaterials.length; index++) {
  75141. var multiMaterial = scene.multiMaterials[index];
  75142. serializationObject.multiMaterials.push(multiMaterial.serialize());
  75143. }
  75144. // Skeletons
  75145. serializationObject.skeletons = [];
  75146. for (index = 0; index < scene.skeletons.length; index++) {
  75147. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  75148. }
  75149. // Transform nodes
  75150. serializationObject.transformNodes = [];
  75151. for (index = 0; index < scene.transformNodes.length; index++) {
  75152. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  75153. }
  75154. // Geometries
  75155. serializationObject.geometries = {};
  75156. serializationObject.geometries.boxes = [];
  75157. serializationObject.geometries.spheres = [];
  75158. serializationObject.geometries.cylinders = [];
  75159. serializationObject.geometries.toruses = [];
  75160. serializationObject.geometries.grounds = [];
  75161. serializationObject.geometries.planes = [];
  75162. serializationObject.geometries.torusKnots = [];
  75163. serializationObject.geometries.vertexData = [];
  75164. serializedGeometries = [];
  75165. var geometries = scene.getGeometries();
  75166. for (index = 0; index < geometries.length; index++) {
  75167. var geometry = geometries[index];
  75168. if (geometry.isReady()) {
  75169. serializeGeometry(geometry, serializationObject.geometries);
  75170. }
  75171. }
  75172. // Meshes
  75173. serializationObject.meshes = [];
  75174. for (index = 0; index < scene.meshes.length; index++) {
  75175. var abstractMesh = scene.meshes[index];
  75176. if (abstractMesh instanceof BABYLON.Mesh) {
  75177. var mesh = abstractMesh;
  75178. if (!mesh.doNotSerialize) {
  75179. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75180. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75181. }
  75182. }
  75183. }
  75184. }
  75185. // Particles Systems
  75186. serializationObject.particleSystems = [];
  75187. for (index = 0; index < scene.particleSystems.length; index++) {
  75188. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  75189. }
  75190. // Lens flares
  75191. serializationObject.lensFlareSystems = [];
  75192. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  75193. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  75194. }
  75195. // Shadows
  75196. serializationObject.shadowGenerators = [];
  75197. for (index = 0; index < scene.lights.length; index++) {
  75198. light = scene.lights[index];
  75199. var shadowGenerator = light.getShadowGenerator();
  75200. if (shadowGenerator) {
  75201. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75202. }
  75203. }
  75204. // Action Manager
  75205. if (scene.actionManager) {
  75206. serializationObject.actions = scene.actionManager.serialize("scene");
  75207. }
  75208. // Audio
  75209. serializationObject.sounds = [];
  75210. for (index = 0; index < scene.soundTracks.length; index++) {
  75211. var soundtrack = scene.soundTracks[index];
  75212. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  75213. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  75214. }
  75215. }
  75216. return serializationObject;
  75217. };
  75218. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  75219. if (withParents === void 0) { withParents = false; }
  75220. if (withChildren === void 0) { withChildren = false; }
  75221. var serializationObject = {};
  75222. SceneSerializer.ClearCache();
  75223. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  75224. if (withParents || withChildren) {
  75225. //deliberate for loop! not for each, appended should be processed as well.
  75226. for (var i = 0; i < toSerialize.length; ++i) {
  75227. if (withChildren) {
  75228. toSerialize[i].getDescendants().forEach(function (node) {
  75229. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  75230. toSerialize.push(node);
  75231. }
  75232. });
  75233. }
  75234. //make sure the array doesn't contain the object already
  75235. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  75236. toSerialize.push(toSerialize[i].parent);
  75237. }
  75238. }
  75239. }
  75240. toSerialize.forEach(function (mesh) {
  75241. finalizeSingleMesh(mesh, serializationObject);
  75242. });
  75243. return serializationObject;
  75244. };
  75245. return SceneSerializer;
  75246. }());
  75247. BABYLON.SceneSerializer = SceneSerializer;
  75248. })(BABYLON || (BABYLON = {}));
  75249. //# sourceMappingURL=babylon.sceneSerializer.js.map
  75250. var BABYLON;
  75251. (function (BABYLON) {
  75252. var ReflectionProbe = /** @class */ (function () {
  75253. function ReflectionProbe(name, size, scene, generateMipMaps) {
  75254. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75255. var _this = this;
  75256. this.name = name;
  75257. this._viewMatrix = BABYLON.Matrix.Identity();
  75258. this._target = BABYLON.Vector3.Zero();
  75259. this._add = BABYLON.Vector3.Zero();
  75260. this.invertYAxis = false;
  75261. this.position = BABYLON.Vector3.Zero();
  75262. this._scene = scene;
  75263. this._scene.reflectionProbes.push(this);
  75264. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  75265. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  75266. switch (faceIndex) {
  75267. case 0:
  75268. _this._add.copyFromFloats(1, 0, 0);
  75269. break;
  75270. case 1:
  75271. _this._add.copyFromFloats(-1, 0, 0);
  75272. break;
  75273. case 2:
  75274. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  75275. break;
  75276. case 3:
  75277. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  75278. break;
  75279. case 4:
  75280. _this._add.copyFromFloats(0, 0, 1);
  75281. break;
  75282. case 5:
  75283. _this._add.copyFromFloats(0, 0, -1);
  75284. break;
  75285. }
  75286. if (_this._attachedMesh) {
  75287. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  75288. }
  75289. _this.position.addToRef(_this._add, _this._target);
  75290. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  75291. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  75292. scene._forcedViewPosition = _this.position;
  75293. });
  75294. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  75295. scene._forcedViewPosition = null;
  75296. scene.updateTransformMatrix(true);
  75297. });
  75298. if (scene.activeCamera) {
  75299. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75300. }
  75301. }
  75302. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  75303. get: function () {
  75304. return this._renderTargetTexture.samples;
  75305. },
  75306. set: function (value) {
  75307. this._renderTargetTexture.samples = value;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  75313. get: function () {
  75314. return this._renderTargetTexture.refreshRate;
  75315. },
  75316. set: function (value) {
  75317. this._renderTargetTexture.refreshRate = value;
  75318. },
  75319. enumerable: true,
  75320. configurable: true
  75321. });
  75322. ReflectionProbe.prototype.getScene = function () {
  75323. return this._scene;
  75324. };
  75325. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  75326. get: function () {
  75327. return this._renderTargetTexture;
  75328. },
  75329. enumerable: true,
  75330. configurable: true
  75331. });
  75332. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  75333. get: function () {
  75334. return this._renderTargetTexture.renderList;
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  75340. this._attachedMesh = mesh;
  75341. };
  75342. /**
  75343. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  75344. *
  75345. * @param renderingGroupId The rendering group id corresponding to its index
  75346. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  75347. */
  75348. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  75349. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  75350. };
  75351. ReflectionProbe.prototype.dispose = function () {
  75352. var index = this._scene.reflectionProbes.indexOf(this);
  75353. if (index !== -1) {
  75354. // Remove from the scene if found
  75355. this._scene.reflectionProbes.splice(index, 1);
  75356. }
  75357. if (this._renderTargetTexture) {
  75358. this._renderTargetTexture.dispose();
  75359. this._renderTargetTexture = null;
  75360. }
  75361. };
  75362. return ReflectionProbe;
  75363. }());
  75364. BABYLON.ReflectionProbe = ReflectionProbe;
  75365. })(BABYLON || (BABYLON = {}));
  75366. //# sourceMappingURL=babylon.reflectionProbe.js.map
  75367. var BABYLON;
  75368. (function (BABYLON) {
  75369. var Layer = /** @class */ (function () {
  75370. function Layer(name, imgUrl, scene, isBackground, color) {
  75371. this.name = name;
  75372. this.scale = new BABYLON.Vector2(1, 1);
  75373. this.offset = new BABYLON.Vector2(0, 0);
  75374. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  75375. this.layerMask = 0x0FFFFFFF;
  75376. this._vertexBuffers = {};
  75377. // Events
  75378. /**
  75379. * An event triggered when the layer is disposed.
  75380. * @type {BABYLON.Observable}
  75381. */
  75382. this.onDisposeObservable = new BABYLON.Observable();
  75383. /**
  75384. * An event triggered before rendering the scene
  75385. * @type {BABYLON.Observable}
  75386. */
  75387. this.onBeforeRenderObservable = new BABYLON.Observable();
  75388. /**
  75389. * An event triggered after rendering the scene
  75390. * @type {BABYLON.Observable}
  75391. */
  75392. this.onAfterRenderObservable = new BABYLON.Observable();
  75393. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  75394. this.isBackground = isBackground === undefined ? true : isBackground;
  75395. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  75396. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  75397. this._scene.layers.push(this);
  75398. var engine = this._scene.getEngine();
  75399. // VBO
  75400. var vertices = [];
  75401. vertices.push(1, 1);
  75402. vertices.push(-1, 1);
  75403. vertices.push(-1, -1);
  75404. vertices.push(1, -1);
  75405. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75407. this._createIndexBuffer();
  75408. // Effects
  75409. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  75410. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  75411. }
  75412. Object.defineProperty(Layer.prototype, "onDispose", {
  75413. set: function (callback) {
  75414. if (this._onDisposeObserver) {
  75415. this.onDisposeObservable.remove(this._onDisposeObserver);
  75416. }
  75417. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  75418. },
  75419. enumerable: true,
  75420. configurable: true
  75421. });
  75422. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  75423. set: function (callback) {
  75424. if (this._onBeforeRenderObserver) {
  75425. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75426. }
  75427. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75428. },
  75429. enumerable: true,
  75430. configurable: true
  75431. });
  75432. Object.defineProperty(Layer.prototype, "onAfterRender", {
  75433. set: function (callback) {
  75434. if (this._onAfterRenderObserver) {
  75435. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75436. }
  75437. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75438. },
  75439. enumerable: true,
  75440. configurable: true
  75441. });
  75442. Layer.prototype._createIndexBuffer = function () {
  75443. var engine = this._scene.getEngine();
  75444. // Indices
  75445. var indices = [];
  75446. indices.push(0);
  75447. indices.push(1);
  75448. indices.push(2);
  75449. indices.push(0);
  75450. indices.push(2);
  75451. indices.push(3);
  75452. this._indexBuffer = engine.createIndexBuffer(indices);
  75453. };
  75454. Layer.prototype._rebuild = function () {
  75455. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75456. if (vb) {
  75457. vb._rebuild();
  75458. }
  75459. this._createIndexBuffer();
  75460. };
  75461. Layer.prototype.render = function () {
  75462. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  75463. // Check
  75464. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  75465. return;
  75466. var engine = this._scene.getEngine();
  75467. this.onBeforeRenderObservable.notifyObservers(this);
  75468. // Render
  75469. engine.enableEffect(currentEffect);
  75470. engine.setState(false);
  75471. // Texture
  75472. currentEffect.setTexture("textureSampler", this.texture);
  75473. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  75474. // Color
  75475. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  75476. // Scale / offset
  75477. currentEffect.setVector2("offset", this.offset);
  75478. currentEffect.setVector2("scale", this.scale);
  75479. // VBOs
  75480. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75481. // Draw order
  75482. if (!this.alphaTest) {
  75483. engine.setAlphaMode(this.alphaBlendingMode);
  75484. engine.draw(true, 0, 6);
  75485. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75486. }
  75487. else {
  75488. engine.draw(true, 0, 6);
  75489. }
  75490. this.onAfterRenderObservable.notifyObservers(this);
  75491. };
  75492. Layer.prototype.dispose = function () {
  75493. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75494. if (vertexBuffer) {
  75495. vertexBuffer.dispose();
  75496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75497. }
  75498. if (this._indexBuffer) {
  75499. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75500. this._indexBuffer = null;
  75501. }
  75502. if (this.texture) {
  75503. this.texture.dispose();
  75504. this.texture = null;
  75505. }
  75506. // Remove from scene
  75507. var index = this._scene.layers.indexOf(this);
  75508. this._scene.layers.splice(index, 1);
  75509. // Callback
  75510. this.onDisposeObservable.notifyObservers(this);
  75511. this.onDisposeObservable.clear();
  75512. this.onAfterRenderObservable.clear();
  75513. this.onBeforeRenderObservable.clear();
  75514. };
  75515. return Layer;
  75516. }());
  75517. BABYLON.Layer = Layer;
  75518. })(BABYLON || (BABYLON = {}));
  75519. //# sourceMappingURL=babylon.layer.js.map
  75520. var BABYLON;
  75521. (function (BABYLON) {
  75522. var TextureTools = /** @class */ (function () {
  75523. function TextureTools() {
  75524. }
  75525. /**
  75526. * Uses the GPU to create a copy texture rescaled at a given size
  75527. * @param texture Texture to copy from
  75528. * @param width Desired width
  75529. * @param height Desired height
  75530. * @return Generated texture
  75531. */
  75532. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  75533. if (useBilinearMode === void 0) { useBilinearMode = true; }
  75534. var scene = texture.getScene();
  75535. var engine = scene.getEngine();
  75536. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  75537. rtt.wrapU = texture.wrapU;
  75538. rtt.wrapV = texture.wrapV;
  75539. rtt.uOffset = texture.uOffset;
  75540. rtt.vOffset = texture.vOffset;
  75541. rtt.uScale = texture.uScale;
  75542. rtt.vScale = texture.vScale;
  75543. rtt.uAng = texture.uAng;
  75544. rtt.vAng = texture.vAng;
  75545. rtt.wAng = texture.wAng;
  75546. rtt.coordinatesIndex = texture.coordinatesIndex;
  75547. rtt.level = texture.level;
  75548. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  75549. rtt._texture.isReady = false;
  75550. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75551. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75552. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75553. passPostProcess.getEffect().executeWhenCompiled(function () {
  75554. passPostProcess.onApply = function (effect) {
  75555. effect.setTexture("textureSampler", texture);
  75556. };
  75557. var internalTexture = rtt.getInternalTexture();
  75558. if (internalTexture) {
  75559. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  75560. engine.unBindFramebuffer(internalTexture);
  75561. rtt.disposeFramebufferObjects();
  75562. passPostProcess.dispose();
  75563. internalTexture.isReady = true;
  75564. }
  75565. });
  75566. return rtt;
  75567. };
  75568. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  75569. if (!scene._environmentBRDFTexture) {
  75570. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75571. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75572. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75573. scene._environmentBRDFTexture = texture;
  75574. }
  75575. return scene._environmentBRDFTexture;
  75576. };
  75577. 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=";
  75578. return TextureTools;
  75579. }());
  75580. BABYLON.TextureTools = TextureTools;
  75581. })(BABYLON || (BABYLON = {}));
  75582. //# sourceMappingURL=babylon.textureTools.js.map
  75583. var BABYLON;
  75584. (function (BABYLON) {
  75585. var FramingBehavior = /** @class */ (function () {
  75586. function FramingBehavior() {
  75587. this._mode = FramingBehavior.FitFrustumSidesMode;
  75588. this._radiusScale = 1.0;
  75589. this._positionScale = 0.5;
  75590. this._defaultElevation = 0.3;
  75591. this._elevationReturnTime = 1500;
  75592. this._elevationReturnWaitTime = 1000;
  75593. this._zoomStopsAnimation = false;
  75594. this._framingTime = 1500;
  75595. this._isPointerDown = false;
  75596. this._lastInteractionTime = -Infinity;
  75597. // Framing control
  75598. this._animatables = new Array();
  75599. this._betaIsAnimating = false;
  75600. }
  75601. Object.defineProperty(FramingBehavior.prototype, "name", {
  75602. get: function () {
  75603. return "Framing";
  75604. },
  75605. enumerable: true,
  75606. configurable: true
  75607. });
  75608. Object.defineProperty(FramingBehavior.prototype, "mode", {
  75609. /**
  75610. * Gets current mode used by the behavior.
  75611. */
  75612. get: function () {
  75613. return this._mode;
  75614. },
  75615. /**
  75616. * Sets the current mode used by the behavior
  75617. */
  75618. set: function (mode) {
  75619. this._mode = mode;
  75620. },
  75621. enumerable: true,
  75622. configurable: true
  75623. });
  75624. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  75625. /**
  75626. * Gets the scale applied to the radius
  75627. */
  75628. get: function () {
  75629. return this._radiusScale;
  75630. },
  75631. /**
  75632. * Sets the scale applied to the radius (1 by default)
  75633. */
  75634. set: function (radius) {
  75635. this._radiusScale = radius;
  75636. },
  75637. enumerable: true,
  75638. configurable: true
  75639. });
  75640. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  75641. /**
  75642. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75643. */
  75644. get: function () {
  75645. return this._positionScale;
  75646. },
  75647. /**
  75648. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75649. */
  75650. set: function (scale) {
  75651. this._positionScale = scale;
  75652. },
  75653. enumerable: true,
  75654. configurable: true
  75655. });
  75656. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  75657. /**
  75658. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75659. * behaviour is triggered, in radians.
  75660. */
  75661. get: function () {
  75662. return this._defaultElevation;
  75663. },
  75664. /**
  75665. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75666. * behaviour is triggered, in radians.
  75667. */
  75668. set: function (elevation) {
  75669. this._defaultElevation = elevation;
  75670. },
  75671. enumerable: true,
  75672. configurable: true
  75673. });
  75674. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  75675. /**
  75676. * Gets the time (in milliseconds) taken to return to the default beta position.
  75677. * Negative value indicates camera should not return to default.
  75678. */
  75679. get: function () {
  75680. return this._elevationReturnTime;
  75681. },
  75682. /**
  75683. * Sets the time (in milliseconds) taken to return to the default beta position.
  75684. * Negative value indicates camera should not return to default.
  75685. */
  75686. set: function (speed) {
  75687. this._elevationReturnTime = speed;
  75688. },
  75689. enumerable: true,
  75690. configurable: true
  75691. });
  75692. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  75693. /**
  75694. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75695. */
  75696. get: function () {
  75697. return this._elevationReturnWaitTime;
  75698. },
  75699. /**
  75700. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75701. */
  75702. set: function (time) {
  75703. this._elevationReturnWaitTime = time;
  75704. },
  75705. enumerable: true,
  75706. configurable: true
  75707. });
  75708. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  75709. /**
  75710. * Gets the flag that indicates if user zooming should stop animation.
  75711. */
  75712. get: function () {
  75713. return this._zoomStopsAnimation;
  75714. },
  75715. /**
  75716. * Sets the flag that indicates if user zooming should stop animation.
  75717. */
  75718. set: function (flag) {
  75719. this._zoomStopsAnimation = flag;
  75720. },
  75721. enumerable: true,
  75722. configurable: true
  75723. });
  75724. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  75725. /**
  75726. * Gets the transition time when framing the mesh, in milliseconds
  75727. */
  75728. get: function () {
  75729. return this._framingTime;
  75730. },
  75731. /**
  75732. * Sets the transition time when framing the mesh, in milliseconds
  75733. */
  75734. set: function (time) {
  75735. this._framingTime = time;
  75736. },
  75737. enumerable: true,
  75738. configurable: true
  75739. });
  75740. FramingBehavior.prototype.init = function () {
  75741. // Do notihng
  75742. };
  75743. FramingBehavior.prototype.attach = function (camera) {
  75744. var _this = this;
  75745. this._attachedCamera = camera;
  75746. var scene = this._attachedCamera.getScene();
  75747. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  75748. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75749. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75750. _this._isPointerDown = true;
  75751. return;
  75752. }
  75753. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75754. _this._isPointerDown = false;
  75755. }
  75756. });
  75757. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  75758. if (mesh) {
  75759. _this.zoomOnMesh(mesh);
  75760. }
  75761. });
  75762. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75763. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75764. _this._applyUserInteraction();
  75765. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  75766. // back to the default position after a given timeout
  75767. _this._maintainCameraAboveGround();
  75768. });
  75769. };
  75770. FramingBehavior.prototype.detach = function () {
  75771. if (!this._attachedCamera) {
  75772. return;
  75773. }
  75774. var scene = this._attachedCamera.getScene();
  75775. if (this._onPrePointerObservableObserver) {
  75776. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75777. }
  75778. if (this._onAfterCheckInputsObserver) {
  75779. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75780. }
  75781. if (this._onMeshTargetChangedObserver) {
  75782. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75783. }
  75784. this._attachedCamera = null;
  75785. };
  75786. /**
  75787. * Targets the given mesh and updates zoom level accordingly.
  75788. * @param mesh The mesh to target.
  75789. * @param radius Optional. If a cached radius position already exists, overrides default.
  75790. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75791. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75792. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75793. */
  75794. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75795. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75796. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75797. mesh.computeWorldMatrix(true);
  75798. var boundingBox = mesh.getBoundingInfo().boundingBox;
  75799. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  75800. };
  75801. /**
  75802. * Targets the given mesh with its children and updates zoom level accordingly.
  75803. * @param mesh The mesh to target.
  75804. * @param radius Optional. If a cached radius position already exists, overrides default.
  75805. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75806. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75807. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75808. */
  75809. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  75810. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75811. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75812. mesh.computeWorldMatrix(true);
  75813. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  75814. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  75815. };
  75816. /**
  75817. * Targets the given meshes with their children and updates zoom level accordingly.
  75818. * @param meshes The mesh to target.
  75819. * @param radius Optional. If a cached radius position already exists, overrides default.
  75820. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75821. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75822. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75823. */
  75824. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  75825. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75826. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75827. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75828. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  75829. for (var i = 0; i < meshes.length; i++) {
  75830. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  75831. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  75832. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  75833. }
  75834. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  75835. };
  75836. /**
  75837. * Targets the given mesh and updates zoom level accordingly.
  75838. * @param mesh The mesh to target.
  75839. * @param radius Optional. If a cached radius position already exists, overrides default.
  75840. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  75841. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  75842. * @param onAnimationEnd Callback triggered at the end of the framing animation
  75843. */
  75844. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  75845. var _this = this;
  75846. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  75847. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  75848. var zoomTarget;
  75849. if (!this._attachedCamera) {
  75850. return;
  75851. }
  75852. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  75853. var bottom = minimumWorld.y;
  75854. var top = maximumWorld.y;
  75855. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  75856. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  75857. if (focusOnOriginXZ) {
  75858. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  75859. }
  75860. else {
  75861. var centerWorld = minimumWorld.add(radiusWorld);
  75862. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  75863. }
  75864. if (!this._vectorTransition) {
  75865. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  75866. }
  75867. this._betaIsAnimating = true;
  75868. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  75869. if (animatable) {
  75870. this._animatables.push(animatable);
  75871. }
  75872. // sets the radius and lower radius bounds
  75873. // Small delta ensures camera is not always at lower zoom limit.
  75874. var radius = 0;
  75875. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  75876. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75877. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  75878. radius = position;
  75879. }
  75880. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75881. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  75882. if (this._attachedCamera.lowerRadiusLimit === null) {
  75883. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  75884. }
  75885. }
  75886. // Set sensibilities
  75887. var extend = maximumWorld.subtract(minimumWorld).length();
  75888. this._attachedCamera.panningSensibility = 5000 / extend;
  75889. this._attachedCamera.wheelPrecision = 100 / radius;
  75890. // transition to new radius
  75891. if (!this._radiusTransition) {
  75892. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75893. }
  75894. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  75895. if (onAnimationEnd) {
  75896. onAnimationEnd();
  75897. }
  75898. if (_this._attachedCamera) {
  75899. _this._attachedCamera.storeState();
  75900. }
  75901. });
  75902. if (animatable) {
  75903. this._animatables.push(animatable);
  75904. }
  75905. };
  75906. /**
  75907. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  75908. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  75909. * frustum width.
  75910. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  75911. * to fully enclose the mesh in the viewing frustum.
  75912. */
  75913. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  75914. var size = maximumWorld.subtract(minimumWorld);
  75915. var boxVectorGlobalDiagonal = size.length();
  75916. var frustumSlope = this._getFrustumSlope();
  75917. // Formula for setting distance
  75918. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  75919. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  75920. // Horizon distance
  75921. var radius = radiusWithoutFraming * this._radiusScale;
  75922. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  75923. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  75924. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  75925. var camera = this._attachedCamera;
  75926. if (!camera) {
  75927. return 0;
  75928. }
  75929. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75930. // Don't exceed the requested limit
  75931. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  75932. }
  75933. // Don't exceed the upper radius limit
  75934. if (camera.upperRadiusLimit) {
  75935. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  75936. }
  75937. return distance;
  75938. };
  75939. /**
  75940. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  75941. * is automatically returned to its default position (expected to be above ground plane).
  75942. */
  75943. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  75944. var _this = this;
  75945. if (this._elevationReturnTime < 0) {
  75946. return;
  75947. }
  75948. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  75949. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  75950. var limitBeta = Math.PI * 0.5;
  75951. // Bring the camera back up if below the ground plane
  75952. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  75953. this._betaIsAnimating = true;
  75954. //Transition to new position
  75955. this.stopAllAnimations();
  75956. if (!this._betaTransition) {
  75957. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75958. }
  75959. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  75960. _this._clearAnimationLocks();
  75961. _this.stopAllAnimations();
  75962. });
  75963. if (animatabe) {
  75964. this._animatables.push(animatabe);
  75965. }
  75966. }
  75967. };
  75968. /**
  75969. * Returns the frustum slope based on the canvas ratio and camera FOV
  75970. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  75971. */
  75972. FramingBehavior.prototype._getFrustumSlope = function () {
  75973. // Calculate the viewport ratio
  75974. // Aspect Ratio is Height/Width.
  75975. var camera = this._attachedCamera;
  75976. if (!camera) {
  75977. return BABYLON.Vector2.Zero();
  75978. }
  75979. var engine = camera.getScene().getEngine();
  75980. var aspectRatio = engine.getAspectRatio(camera);
  75981. // Camera FOV is the vertical field of view (top-bottom) in radians.
  75982. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  75983. var frustumSlopeY = Math.tan(camera.fov / 2);
  75984. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  75985. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  75986. // along the forward vector.
  75987. var frustumSlopeX = frustumSlopeY * aspectRatio;
  75988. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  75989. };
  75990. /**
  75991. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  75992. */
  75993. FramingBehavior.prototype._clearAnimationLocks = function () {
  75994. this._betaIsAnimating = false;
  75995. };
  75996. /**
  75997. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75998. */
  75999. FramingBehavior.prototype._applyUserInteraction = function () {
  76000. if (this.isUserIsMoving) {
  76001. this._lastInteractionTime = BABYLON.Tools.Now;
  76002. this.stopAllAnimations();
  76003. this._clearAnimationLocks();
  76004. }
  76005. };
  76006. /**
  76007. * Stops and removes all animations that have been applied to the camera
  76008. */
  76009. FramingBehavior.prototype.stopAllAnimations = function () {
  76010. if (this._attachedCamera) {
  76011. this._attachedCamera.animations = [];
  76012. }
  76013. while (this._animatables.length) {
  76014. if (this._animatables[0]) {
  76015. this._animatables[0].onAnimationEnd = null;
  76016. this._animatables[0].stop();
  76017. }
  76018. this._animatables.shift();
  76019. }
  76020. };
  76021. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  76022. /**
  76023. * Gets a value indicating if the user is moving the camera
  76024. */
  76025. get: function () {
  76026. if (!this._attachedCamera) {
  76027. return false;
  76028. }
  76029. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76030. this._attachedCamera.inertialBetaOffset !== 0 ||
  76031. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76032. this._attachedCamera.inertialPanningX !== 0 ||
  76033. this._attachedCamera.inertialPanningY !== 0 ||
  76034. this._isPointerDown;
  76035. },
  76036. enumerable: true,
  76037. configurable: true
  76038. });
  76039. /**
  76040. * The easing function used by animations
  76041. */
  76042. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  76043. /**
  76044. * The easing mode used by animations
  76045. */
  76046. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  76047. // Statics
  76048. /**
  76049. * The camera can move all the way towards the mesh.
  76050. */
  76051. FramingBehavior.IgnoreBoundsSizeMode = 0;
  76052. /**
  76053. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  76054. */
  76055. FramingBehavior.FitFrustumSidesMode = 1;
  76056. return FramingBehavior;
  76057. }());
  76058. BABYLON.FramingBehavior = FramingBehavior;
  76059. })(BABYLON || (BABYLON = {}));
  76060. //# sourceMappingURL=babylon.framingBehavior.js.map
  76061. var BABYLON;
  76062. (function (BABYLON) {
  76063. /**
  76064. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  76065. */
  76066. var BouncingBehavior = /** @class */ (function () {
  76067. function BouncingBehavior() {
  76068. /**
  76069. * The duration of the animation, in milliseconds
  76070. */
  76071. this.transitionDuration = 450;
  76072. /**
  76073. * Length of the distance animated by the transition when lower radius is reached
  76074. */
  76075. this.lowerRadiusTransitionRange = 2;
  76076. /**
  76077. * Length of the distance animated by the transition when upper radius is reached
  76078. */
  76079. this.upperRadiusTransitionRange = -2;
  76080. this._autoTransitionRange = false;
  76081. // Animations
  76082. this._radiusIsAnimating = false;
  76083. this._radiusBounceTransition = null;
  76084. this._animatables = new Array();
  76085. }
  76086. Object.defineProperty(BouncingBehavior.prototype, "name", {
  76087. get: function () {
  76088. return "Bouncing";
  76089. },
  76090. enumerable: true,
  76091. configurable: true
  76092. });
  76093. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  76094. /**
  76095. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76096. */
  76097. get: function () {
  76098. return this._autoTransitionRange;
  76099. },
  76100. /**
  76101. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76102. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  76103. */
  76104. set: function (value) {
  76105. var _this = this;
  76106. if (this._autoTransitionRange === value) {
  76107. return;
  76108. }
  76109. this._autoTransitionRange = value;
  76110. var camera = this._attachedCamera;
  76111. if (!camera) {
  76112. return;
  76113. }
  76114. if (value) {
  76115. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76116. if (!mesh) {
  76117. return;
  76118. }
  76119. mesh.computeWorldMatrix(true);
  76120. var diagonal = mesh.getBoundingInfo().diagonalLength;
  76121. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  76122. _this.upperRadiusTransitionRange = diagonal * 0.05;
  76123. });
  76124. }
  76125. else if (this._onMeshTargetChangedObserver) {
  76126. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76127. }
  76128. },
  76129. enumerable: true,
  76130. configurable: true
  76131. });
  76132. BouncingBehavior.prototype.init = function () {
  76133. // Do notihng
  76134. };
  76135. BouncingBehavior.prototype.attach = function (camera) {
  76136. var _this = this;
  76137. this._attachedCamera = camera;
  76138. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76139. if (!_this._attachedCamera) {
  76140. return;
  76141. }
  76142. // Add the bounce animation to the lower radius limit
  76143. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  76144. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  76145. }
  76146. // Add the bounce animation to the upper radius limit
  76147. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  76148. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  76149. }
  76150. });
  76151. };
  76152. BouncingBehavior.prototype.detach = function () {
  76153. if (!this._attachedCamera) {
  76154. return;
  76155. }
  76156. if (this._onAfterCheckInputsObserver) {
  76157. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76158. }
  76159. if (this._onMeshTargetChangedObserver) {
  76160. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76161. }
  76162. this._attachedCamera = null;
  76163. };
  76164. /**
  76165. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  76166. * @param radiusLimit The limit to check against.
  76167. * @return Bool to indicate if at limit.
  76168. */
  76169. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  76170. if (!this._attachedCamera) {
  76171. return false;
  76172. }
  76173. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  76174. return true;
  76175. }
  76176. return false;
  76177. };
  76178. /**
  76179. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  76180. * @param radiusDelta The delta by which to animate to. Can be negative.
  76181. */
  76182. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  76183. var _this = this;
  76184. if (!this._attachedCamera) {
  76185. return;
  76186. }
  76187. if (!this._radiusBounceTransition) {
  76188. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  76189. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  76190. }
  76191. // Prevent zoom until bounce has completed
  76192. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  76193. this._attachedCamera.wheelPrecision = Infinity;
  76194. this._attachedCamera.inertialRadiusOffset = 0;
  76195. // Animate to the radius limit
  76196. this.stopAllAnimations();
  76197. this._radiusIsAnimating = true;
  76198. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  76199. if (animatable) {
  76200. this._animatables.push(animatable);
  76201. }
  76202. };
  76203. /**
  76204. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  76205. */
  76206. BouncingBehavior.prototype._clearAnimationLocks = function () {
  76207. this._radiusIsAnimating = false;
  76208. if (this._attachedCamera) {
  76209. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  76210. }
  76211. };
  76212. /**
  76213. * Stops and removes all animations that have been applied to the camera
  76214. */
  76215. BouncingBehavior.prototype.stopAllAnimations = function () {
  76216. if (this._attachedCamera) {
  76217. this._attachedCamera.animations = [];
  76218. }
  76219. while (this._animatables.length) {
  76220. this._animatables[0].onAnimationEnd = null;
  76221. this._animatables[0].stop();
  76222. this._animatables.shift();
  76223. }
  76224. };
  76225. /**
  76226. * The easing function used by animations
  76227. */
  76228. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  76229. /**
  76230. * The easing mode used by animations
  76231. */
  76232. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  76233. return BouncingBehavior;
  76234. }());
  76235. BABYLON.BouncingBehavior = BouncingBehavior;
  76236. })(BABYLON || (BABYLON = {}));
  76237. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  76238. var BABYLON;
  76239. (function (BABYLON) {
  76240. var AutoRotationBehavior = /** @class */ (function () {
  76241. function AutoRotationBehavior() {
  76242. this._zoomStopsAnimation = false;
  76243. this._idleRotationSpeed = 0.05;
  76244. this._idleRotationWaitTime = 2000;
  76245. this._idleRotationSpinupTime = 2000;
  76246. this._isPointerDown = false;
  76247. this._lastFrameTime = null;
  76248. this._lastInteractionTime = -Infinity;
  76249. this._cameraRotationSpeed = 0;
  76250. this._lastFrameRadius = 0;
  76251. }
  76252. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  76253. get: function () {
  76254. return "AutoRotation";
  76255. },
  76256. enumerable: true,
  76257. configurable: true
  76258. });
  76259. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  76260. /**
  76261. * Gets the flag that indicates if user zooming should stop animation.
  76262. */
  76263. get: function () {
  76264. return this._zoomStopsAnimation;
  76265. },
  76266. /**
  76267. * Sets the flag that indicates if user zooming should stop animation.
  76268. */
  76269. set: function (flag) {
  76270. this._zoomStopsAnimation = flag;
  76271. },
  76272. enumerable: true,
  76273. configurable: true
  76274. });
  76275. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  76276. /**
  76277. * Gets the default speed at which the camera rotates around the model.
  76278. */
  76279. get: function () {
  76280. return this._idleRotationSpeed;
  76281. },
  76282. /**
  76283. * Sets the default speed at which the camera rotates around the model.
  76284. */
  76285. set: function (speed) {
  76286. this._idleRotationSpeed = speed;
  76287. },
  76288. enumerable: true,
  76289. configurable: true
  76290. });
  76291. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  76292. /**
  76293. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  76294. */
  76295. get: function () {
  76296. return this._idleRotationWaitTime;
  76297. },
  76298. /**
  76299. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  76300. */
  76301. set: function (time) {
  76302. this._idleRotationWaitTime = time;
  76303. },
  76304. enumerable: true,
  76305. configurable: true
  76306. });
  76307. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  76308. /**
  76309. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76310. */
  76311. get: function () {
  76312. return this._idleRotationSpinupTime;
  76313. },
  76314. /**
  76315. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76316. */
  76317. set: function (time) {
  76318. this._idleRotationSpinupTime = time;
  76319. },
  76320. enumerable: true,
  76321. configurable: true
  76322. });
  76323. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  76324. /**
  76325. * Gets a value indicating if the camera is currently rotating because of this behavior
  76326. */
  76327. get: function () {
  76328. return Math.abs(this._cameraRotationSpeed) > 0;
  76329. },
  76330. enumerable: true,
  76331. configurable: true
  76332. });
  76333. AutoRotationBehavior.prototype.init = function () {
  76334. // Do notihng
  76335. };
  76336. AutoRotationBehavior.prototype.attach = function (camera) {
  76337. var _this = this;
  76338. this._attachedCamera = camera;
  76339. var scene = this._attachedCamera.getScene();
  76340. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76341. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76342. _this._isPointerDown = true;
  76343. return;
  76344. }
  76345. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76346. _this._isPointerDown = false;
  76347. }
  76348. });
  76349. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76350. var now = BABYLON.Tools.Now;
  76351. var dt = 0;
  76352. if (_this._lastFrameTime != null) {
  76353. dt = now - _this._lastFrameTime;
  76354. }
  76355. _this._lastFrameTime = now;
  76356. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76357. _this._applyUserInteraction();
  76358. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  76359. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  76360. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  76361. // Step camera rotation by rotation speed
  76362. if (_this._attachedCamera) {
  76363. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  76364. }
  76365. });
  76366. };
  76367. AutoRotationBehavior.prototype.detach = function () {
  76368. if (!this._attachedCamera) {
  76369. return;
  76370. }
  76371. var scene = this._attachedCamera.getScene();
  76372. if (this._onPrePointerObservableObserver) {
  76373. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76374. }
  76375. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76376. this._attachedCamera = null;
  76377. };
  76378. /**
  76379. * Returns true if user is scrolling.
  76380. * @return true if user is scrolling.
  76381. */
  76382. AutoRotationBehavior.prototype._userIsZooming = function () {
  76383. if (!this._attachedCamera) {
  76384. return false;
  76385. }
  76386. return this._attachedCamera.inertialRadiusOffset !== 0;
  76387. };
  76388. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  76389. if (!this._attachedCamera) {
  76390. return false;
  76391. }
  76392. var zoomHasHitLimit = false;
  76393. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  76394. zoomHasHitLimit = true;
  76395. }
  76396. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  76397. this._lastFrameRadius = this._attachedCamera.radius;
  76398. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  76399. };
  76400. /**
  76401. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76402. */
  76403. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  76404. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  76405. this._lastInteractionTime = BABYLON.Tools.Now;
  76406. }
  76407. };
  76408. // Tools
  76409. AutoRotationBehavior.prototype._userIsMoving = function () {
  76410. if (!this._attachedCamera) {
  76411. return false;
  76412. }
  76413. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76414. this._attachedCamera.inertialBetaOffset !== 0 ||
  76415. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76416. this._attachedCamera.inertialPanningX !== 0 ||
  76417. this._attachedCamera.inertialPanningY !== 0 ||
  76418. this._isPointerDown;
  76419. };
  76420. return AutoRotationBehavior;
  76421. }());
  76422. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  76423. })(BABYLON || (BABYLON = {}));
  76424. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  76425. var BABYLON;
  76426. (function (BABYLON) {
  76427. /**
  76428. * This class can be used to get instrumentation data from a Babylon engine
  76429. */
  76430. var EngineInstrumentation = /** @class */ (function () {
  76431. function EngineInstrumentation(engine) {
  76432. this.engine = engine;
  76433. this._captureGPUFrameTime = false;
  76434. this._gpuFrameTime = new BABYLON.PerfCounter();
  76435. this._captureShaderCompilationTime = false;
  76436. this._shaderCompilationTime = new BABYLON.PerfCounter();
  76437. // Observers
  76438. this._onBeginFrameObserver = null;
  76439. this._onEndFrameObserver = null;
  76440. this._onBeforeShaderCompilationObserver = null;
  76441. this._onAfterShaderCompilationObserver = null;
  76442. }
  76443. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  76444. // Properties
  76445. /**
  76446. * Gets the perf counter used for GPU frame time
  76447. */
  76448. get: function () {
  76449. return this._gpuFrameTime;
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  76455. /**
  76456. * Gets the GPU frame time capture status
  76457. */
  76458. get: function () {
  76459. return this._captureGPUFrameTime;
  76460. },
  76461. /**
  76462. * Enable or disable the GPU frame time capture
  76463. */
  76464. set: function (value) {
  76465. var _this = this;
  76466. if (value === this._captureGPUFrameTime) {
  76467. return;
  76468. }
  76469. this._captureGPUFrameTime = value;
  76470. if (value) {
  76471. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  76472. if (!_this._gpuFrameTimeToken) {
  76473. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  76474. }
  76475. });
  76476. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  76477. if (!_this._gpuFrameTimeToken) {
  76478. return;
  76479. }
  76480. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  76481. if (time > -1) {
  76482. _this._gpuFrameTimeToken = null;
  76483. _this._gpuFrameTime.fetchNewFrame();
  76484. _this._gpuFrameTime.addCount(time, true);
  76485. }
  76486. });
  76487. }
  76488. else {
  76489. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76490. this._onBeginFrameObserver = null;
  76491. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76492. this._onEndFrameObserver = null;
  76493. }
  76494. },
  76495. enumerable: true,
  76496. configurable: true
  76497. });
  76498. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  76499. /**
  76500. * Gets the perf counter used for shader compilation time
  76501. */
  76502. get: function () {
  76503. return this._shaderCompilationTime;
  76504. },
  76505. enumerable: true,
  76506. configurable: true
  76507. });
  76508. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  76509. /**
  76510. * Gets the shader compilation time capture status
  76511. */
  76512. get: function () {
  76513. return this._captureShaderCompilationTime;
  76514. },
  76515. /**
  76516. * Enable or disable the shader compilation time capture
  76517. */
  76518. set: function (value) {
  76519. var _this = this;
  76520. if (value === this._captureShaderCompilationTime) {
  76521. return;
  76522. }
  76523. this._captureShaderCompilationTime = value;
  76524. if (value) {
  76525. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  76526. _this._shaderCompilationTime.fetchNewFrame();
  76527. _this._shaderCompilationTime.beginMonitoring();
  76528. });
  76529. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  76530. _this._shaderCompilationTime.endMonitoring();
  76531. });
  76532. }
  76533. else {
  76534. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76535. this._onBeforeShaderCompilationObserver = null;
  76536. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76537. this._onAfterShaderCompilationObserver = null;
  76538. }
  76539. },
  76540. enumerable: true,
  76541. configurable: true
  76542. });
  76543. EngineInstrumentation.prototype.dispose = function () {
  76544. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76545. this._onBeginFrameObserver = null;
  76546. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76547. this._onEndFrameObserver = null;
  76548. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76549. this._onBeforeShaderCompilationObserver = null;
  76550. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76551. this._onAfterShaderCompilationObserver = null;
  76552. this.engine = null;
  76553. };
  76554. return EngineInstrumentation;
  76555. }());
  76556. BABYLON.EngineInstrumentation = EngineInstrumentation;
  76557. })(BABYLON || (BABYLON = {}));
  76558. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  76559. var BABYLON;
  76560. (function (BABYLON) {
  76561. /**
  76562. * This class can be used to get instrumentation data from a Babylon engine
  76563. */
  76564. var SceneInstrumentation = /** @class */ (function () {
  76565. function SceneInstrumentation(scene) {
  76566. var _this = this;
  76567. this.scene = scene;
  76568. this._captureActiveMeshesEvaluationTime = false;
  76569. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  76570. this._captureRenderTargetsRenderTime = false;
  76571. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  76572. this._captureFrameTime = false;
  76573. this._frameTime = new BABYLON.PerfCounter();
  76574. this._captureRenderTime = false;
  76575. this._renderTime = new BABYLON.PerfCounter();
  76576. this._captureInterFrameTime = false;
  76577. this._interFrameTime = new BABYLON.PerfCounter();
  76578. this._captureParticlesRenderTime = false;
  76579. this._particlesRenderTime = new BABYLON.PerfCounter();
  76580. this._captureSpritesRenderTime = false;
  76581. this._spritesRenderTime = new BABYLON.PerfCounter();
  76582. this._capturePhysicsTime = false;
  76583. this._physicsTime = new BABYLON.PerfCounter();
  76584. this._captureAnimationsTime = false;
  76585. this._animationsTime = new BABYLON.PerfCounter();
  76586. // Observers
  76587. this._onBeforeActiveMeshesEvaluationObserver = null;
  76588. this._onAfterActiveMeshesEvaluationObserver = null;
  76589. this._onBeforeRenderTargetsRenderObserver = null;
  76590. this._onAfterRenderTargetsRenderObserver = null;
  76591. this._onAfterRenderObserver = null;
  76592. this._onBeforeDrawPhaseObserver = null;
  76593. this._onAfterDrawPhaseObserver = null;
  76594. this._onBeforeAnimationsObserver = null;
  76595. this._onBeforeParticlesRenderingObserver = null;
  76596. this._onAfterParticlesRenderingObserver = null;
  76597. this._onBeforeSpritesRenderingObserver = null;
  76598. this._onAfterSpritesRenderingObserver = null;
  76599. this._onBeforePhysicsObserver = null;
  76600. this._onAfterPhysicsObserver = null;
  76601. this._onAfterAnimationsObserver = null;
  76602. // Before render
  76603. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  76604. if (_this._captureActiveMeshesEvaluationTime) {
  76605. _this._activeMeshesEvaluationTime.fetchNewFrame();
  76606. }
  76607. if (_this._captureRenderTargetsRenderTime) {
  76608. _this._renderTargetsRenderTime.fetchNewFrame();
  76609. }
  76610. if (_this._captureFrameTime) {
  76611. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  76612. _this._frameTime.beginMonitoring();
  76613. }
  76614. if (_this._captureInterFrameTime) {
  76615. _this._interFrameTime.endMonitoring();
  76616. }
  76617. if (_this._captureParticlesRenderTime) {
  76618. _this._particlesRenderTime.fetchNewFrame();
  76619. }
  76620. if (_this._captureSpritesRenderTime) {
  76621. _this._spritesRenderTime.fetchNewFrame();
  76622. }
  76623. if (_this._captureAnimationsTime) {
  76624. _this._animationsTime.beginMonitoring();
  76625. }
  76626. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  76627. });
  76628. // After render
  76629. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  76630. if (_this._captureFrameTime) {
  76631. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  76632. _this._frameTime.endMonitoring();
  76633. }
  76634. if (_this._captureRenderTime) {
  76635. _this._renderTime.endMonitoring(false);
  76636. }
  76637. if (_this._captureInterFrameTime) {
  76638. _this._interFrameTime.beginMonitoring();
  76639. }
  76640. });
  76641. }
  76642. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  76643. // Properties
  76644. /**
  76645. * Gets the perf counter used for active meshes evaluation time
  76646. */
  76647. get: function () {
  76648. return this._activeMeshesEvaluationTime;
  76649. },
  76650. enumerable: true,
  76651. configurable: true
  76652. });
  76653. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  76654. /**
  76655. * Gets the active meshes evaluation time capture status
  76656. */
  76657. get: function () {
  76658. return this._captureActiveMeshesEvaluationTime;
  76659. },
  76660. /**
  76661. * Enable or disable the active meshes evaluation time capture
  76662. */
  76663. set: function (value) {
  76664. var _this = this;
  76665. if (value === this._captureActiveMeshesEvaluationTime) {
  76666. return;
  76667. }
  76668. this._captureActiveMeshesEvaluationTime = value;
  76669. if (value) {
  76670. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  76671. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  76672. _this._activeMeshesEvaluationTime.beginMonitoring();
  76673. });
  76674. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  76675. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  76676. _this._activeMeshesEvaluationTime.endMonitoring();
  76677. });
  76678. }
  76679. else {
  76680. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76681. this._onBeforeActiveMeshesEvaluationObserver = null;
  76682. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76683. this._onAfterActiveMeshesEvaluationObserver = null;
  76684. }
  76685. },
  76686. enumerable: true,
  76687. configurable: true
  76688. });
  76689. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  76690. /**
  76691. * Gets the perf counter used for render targets render time
  76692. */
  76693. get: function () {
  76694. return this._renderTargetsRenderTime;
  76695. },
  76696. enumerable: true,
  76697. configurable: true
  76698. });
  76699. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  76700. /**
  76701. * Gets the render targets render time capture status
  76702. */
  76703. get: function () {
  76704. return this._captureRenderTargetsRenderTime;
  76705. },
  76706. /**
  76707. * Enable or disable the render targets render time capture
  76708. */
  76709. set: function (value) {
  76710. var _this = this;
  76711. if (value === this._captureRenderTargetsRenderTime) {
  76712. return;
  76713. }
  76714. this._captureRenderTargetsRenderTime = value;
  76715. if (value) {
  76716. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  76717. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  76718. _this._renderTargetsRenderTime.beginMonitoring();
  76719. });
  76720. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  76721. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  76722. _this._renderTargetsRenderTime.endMonitoring(false);
  76723. });
  76724. }
  76725. else {
  76726. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76727. this._onBeforeRenderTargetsRenderObserver = null;
  76728. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76729. this._onAfterRenderTargetsRenderObserver = null;
  76730. }
  76731. },
  76732. enumerable: true,
  76733. configurable: true
  76734. });
  76735. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  76736. /**
  76737. * Gets the perf counter used for particles render time
  76738. */
  76739. get: function () {
  76740. return this._particlesRenderTime;
  76741. },
  76742. enumerable: true,
  76743. configurable: true
  76744. });
  76745. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  76746. /**
  76747. * Gets the particles render time capture status
  76748. */
  76749. get: function () {
  76750. return this._captureParticlesRenderTime;
  76751. },
  76752. /**
  76753. * Enable or disable the particles render time capture
  76754. */
  76755. set: function (value) {
  76756. var _this = this;
  76757. if (value === this._captureParticlesRenderTime) {
  76758. return;
  76759. }
  76760. this._captureParticlesRenderTime = value;
  76761. if (value) {
  76762. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  76763. BABYLON.Tools.StartPerformanceCounter("Particles");
  76764. _this._particlesRenderTime.beginMonitoring();
  76765. });
  76766. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  76767. BABYLON.Tools.EndPerformanceCounter("Particles");
  76768. _this._particlesRenderTime.endMonitoring(false);
  76769. });
  76770. }
  76771. else {
  76772. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  76773. this._onBeforeParticlesRenderingObserver = null;
  76774. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  76775. this._onAfterParticlesRenderingObserver = null;
  76776. }
  76777. },
  76778. enumerable: true,
  76779. configurable: true
  76780. });
  76781. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  76782. /**
  76783. * Gets the perf counter used for sprites render time
  76784. */
  76785. get: function () {
  76786. return this._spritesRenderTime;
  76787. },
  76788. enumerable: true,
  76789. configurable: true
  76790. });
  76791. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  76792. /**
  76793. * Gets the sprites render time capture status
  76794. */
  76795. get: function () {
  76796. return this._captureSpritesRenderTime;
  76797. },
  76798. /**
  76799. * Enable or disable the sprites render time capture
  76800. */
  76801. set: function (value) {
  76802. var _this = this;
  76803. if (value === this._captureSpritesRenderTime) {
  76804. return;
  76805. }
  76806. this._captureSpritesRenderTime = value;
  76807. if (value) {
  76808. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  76809. BABYLON.Tools.StartPerformanceCounter("Sprites");
  76810. _this._spritesRenderTime.beginMonitoring();
  76811. });
  76812. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  76813. BABYLON.Tools.EndPerformanceCounter("Sprites");
  76814. _this._spritesRenderTime.endMonitoring(false);
  76815. });
  76816. }
  76817. else {
  76818. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  76819. this._onBeforeSpritesRenderingObserver = null;
  76820. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  76821. this._onAfterSpritesRenderingObserver = null;
  76822. }
  76823. },
  76824. enumerable: true,
  76825. configurable: true
  76826. });
  76827. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  76828. /**
  76829. * Gets the perf counter used for physics time
  76830. */
  76831. get: function () {
  76832. return this._physicsTime;
  76833. },
  76834. enumerable: true,
  76835. configurable: true
  76836. });
  76837. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  76838. /**
  76839. * Gets the physics time capture status
  76840. */
  76841. get: function () {
  76842. return this._capturePhysicsTime;
  76843. },
  76844. /**
  76845. * Enable or disable the physics time capture
  76846. */
  76847. set: function (value) {
  76848. var _this = this;
  76849. if (value === this._capturePhysicsTime) {
  76850. return;
  76851. }
  76852. this._capturePhysicsTime = value;
  76853. if (value) {
  76854. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  76855. BABYLON.Tools.StartPerformanceCounter("Physics");
  76856. _this._physicsTime.beginMonitoring();
  76857. });
  76858. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  76859. BABYLON.Tools.EndPerformanceCounter("Physics");
  76860. _this._physicsTime.endMonitoring();
  76861. });
  76862. }
  76863. else {
  76864. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  76865. this._onBeforePhysicsObserver = null;
  76866. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  76867. this._onAfterPhysicsObserver = null;
  76868. }
  76869. },
  76870. enumerable: true,
  76871. configurable: true
  76872. });
  76873. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  76874. /**
  76875. * Gets the perf counter used for animations time
  76876. */
  76877. get: function () {
  76878. return this._animationsTime;
  76879. },
  76880. enumerable: true,
  76881. configurable: true
  76882. });
  76883. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  76884. /**
  76885. * Gets the animations time capture status
  76886. */
  76887. get: function () {
  76888. return this._captureAnimationsTime;
  76889. },
  76890. /**
  76891. * Enable or disable the animations time capture
  76892. */
  76893. set: function (value) {
  76894. var _this = this;
  76895. if (value === this._captureAnimationsTime) {
  76896. return;
  76897. }
  76898. this._captureAnimationsTime = value;
  76899. if (value) {
  76900. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  76901. _this._animationsTime.endMonitoring();
  76902. });
  76903. }
  76904. else {
  76905. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76906. this._onAfterAnimationsObserver = null;
  76907. }
  76908. },
  76909. enumerable: true,
  76910. configurable: true
  76911. });
  76912. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  76913. /**
  76914. * Gets the perf counter used for frame time capture
  76915. */
  76916. get: function () {
  76917. return this._frameTime;
  76918. },
  76919. enumerable: true,
  76920. configurable: true
  76921. });
  76922. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  76923. /**
  76924. * Gets the frame time capture status
  76925. */
  76926. get: function () {
  76927. return this._captureFrameTime;
  76928. },
  76929. /**
  76930. * Enable or disable the frame time capture
  76931. */
  76932. set: function (value) {
  76933. this._captureFrameTime = value;
  76934. },
  76935. enumerable: true,
  76936. configurable: true
  76937. });
  76938. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  76939. /**
  76940. * Gets the perf counter used for inter-frames time capture
  76941. */
  76942. get: function () {
  76943. return this._interFrameTime;
  76944. },
  76945. enumerable: true,
  76946. configurable: true
  76947. });
  76948. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  76949. /**
  76950. * Gets the inter-frames time capture status
  76951. */
  76952. get: function () {
  76953. return this._captureInterFrameTime;
  76954. },
  76955. /**
  76956. * Enable or disable the inter-frames time capture
  76957. */
  76958. set: function (value) {
  76959. this._captureInterFrameTime = value;
  76960. },
  76961. enumerable: true,
  76962. configurable: true
  76963. });
  76964. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  76965. /**
  76966. * Gets the perf counter used for render time capture
  76967. */
  76968. get: function () {
  76969. return this._renderTime;
  76970. },
  76971. enumerable: true,
  76972. configurable: true
  76973. });
  76974. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  76975. /**
  76976. * Gets the render time capture status
  76977. */
  76978. get: function () {
  76979. return this._captureRenderTime;
  76980. },
  76981. /**
  76982. * Enable or disable the render time capture
  76983. */
  76984. set: function (value) {
  76985. var _this = this;
  76986. if (value === this._captureRenderTime) {
  76987. return;
  76988. }
  76989. this._captureRenderTime = value;
  76990. if (value) {
  76991. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  76992. _this._renderTime.beginMonitoring();
  76993. BABYLON.Tools.StartPerformanceCounter("Main render");
  76994. });
  76995. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  76996. _this._renderTime.endMonitoring(false);
  76997. BABYLON.Tools.EndPerformanceCounter("Main render");
  76998. });
  76999. }
  77000. else {
  77001. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77002. this._onBeforeDrawPhaseObserver = null;
  77003. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77004. this._onAfterDrawPhaseObserver = null;
  77005. }
  77006. },
  77007. enumerable: true,
  77008. configurable: true
  77009. });
  77010. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  77011. /**
  77012. * Gets the perf counter used for frame time capture
  77013. */
  77014. get: function () {
  77015. return this.scene.getEngine()._drawCalls;
  77016. },
  77017. enumerable: true,
  77018. configurable: true
  77019. });
  77020. SceneInstrumentation.prototype.dispose = function () {
  77021. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77022. this._onAfterRenderObserver = null;
  77023. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77024. this._onBeforeActiveMeshesEvaluationObserver = null;
  77025. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77026. this._onAfterActiveMeshesEvaluationObserver = null;
  77027. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77028. this._onBeforeRenderTargetsRenderObserver = null;
  77029. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77030. this._onAfterRenderTargetsRenderObserver = null;
  77031. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  77032. this._onBeforeAnimationsObserver = null;
  77033. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77034. this._onBeforeParticlesRenderingObserver = null;
  77035. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77036. this._onAfterParticlesRenderingObserver = null;
  77037. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77038. this._onBeforeSpritesRenderingObserver = null;
  77039. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77040. this._onAfterSpritesRenderingObserver = null;
  77041. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77042. this._onBeforeDrawPhaseObserver = null;
  77043. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77044. this._onAfterDrawPhaseObserver = null;
  77045. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77046. this._onBeforePhysicsObserver = null;
  77047. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77048. this._onAfterPhysicsObserver = null;
  77049. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77050. this._onAfterAnimationsObserver = null;
  77051. this.scene = null;
  77052. };
  77053. return SceneInstrumentation;
  77054. }());
  77055. BABYLON.SceneInstrumentation = SceneInstrumentation;
  77056. })(BABYLON || (BABYLON = {}));
  77057. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  77058. var BABYLON;
  77059. (function (BABYLON) {
  77060. var _TimeToken = /** @class */ (function () {
  77061. function _TimeToken() {
  77062. this._timeElapsedQueryEnded = false;
  77063. }
  77064. return _TimeToken;
  77065. }());
  77066. BABYLON._TimeToken = _TimeToken;
  77067. })(BABYLON || (BABYLON = {}));
  77068. //# sourceMappingURL=babylon.timeToken.js.map
  77069. var BABYLON;
  77070. (function (BABYLON) {
  77071. /**
  77072. * Background material defines definition.
  77073. */
  77074. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  77075. __extends(BackgroundMaterialDefines, _super);
  77076. /**
  77077. * Constructor of the defines.
  77078. */
  77079. function BackgroundMaterialDefines() {
  77080. var _this = _super.call(this) || this;
  77081. /**
  77082. * True if the diffuse texture is in use.
  77083. */
  77084. _this.DIFFUSE = false;
  77085. /**
  77086. * The direct UV channel to use.
  77087. */
  77088. _this.DIFFUSEDIRECTUV = 0;
  77089. /**
  77090. * True if the diffuse texture is in gamma space.
  77091. */
  77092. _this.GAMMADIFFUSE = false;
  77093. /**
  77094. * True if the diffuse texture has opacity in the alpha channel.
  77095. */
  77096. _this.DIFFUSEHASALPHA = false;
  77097. /**
  77098. * True if you want the material to fade to transparent at grazing angle.
  77099. */
  77100. _this.OPACITYFRESNEL = false;
  77101. /**
  77102. * True if an extra blur needs to be added in the reflection.
  77103. */
  77104. _this.REFLECTIONBLUR = false;
  77105. /**
  77106. * True if you want the material to fade to reflection at grazing angle.
  77107. */
  77108. _this.REFLECTIONFRESNEL = false;
  77109. /**
  77110. * True if you want the material to falloff as far as you move away from the scene center.
  77111. */
  77112. _this.REFLECTIONFALLOFF = false;
  77113. /**
  77114. * False if the current Webgl implementation does not support the texture lod extension.
  77115. */
  77116. _this.TEXTURELODSUPPORT = false;
  77117. /**
  77118. * True to ensure the data are premultiplied.
  77119. */
  77120. _this.PREMULTIPLYALPHA = false;
  77121. /**
  77122. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  77123. */
  77124. _this.USERGBCOLOR = false;
  77125. /**
  77126. * True to add noise in order to reduce the banding effect.
  77127. */
  77128. _this.NOISE = false;
  77129. // Image Processing Configuration.
  77130. _this.IMAGEPROCESSING = false;
  77131. _this.VIGNETTE = false;
  77132. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  77133. _this.VIGNETTEBLENDMODEOPAQUE = false;
  77134. _this.TONEMAPPING = false;
  77135. _this.CONTRAST = false;
  77136. _this.COLORCURVES = false;
  77137. _this.COLORGRADING = false;
  77138. _this.COLORGRADING3D = false;
  77139. _this.SAMPLER3DGREENDEPTH = false;
  77140. _this.SAMPLER3DBGRMAP = false;
  77141. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  77142. _this.EXPOSURE = false;
  77143. // Reflection.
  77144. _this.REFLECTION = false;
  77145. _this.REFLECTIONMAP_3D = false;
  77146. _this.REFLECTIONMAP_SPHERICAL = false;
  77147. _this.REFLECTIONMAP_PLANAR = false;
  77148. _this.REFLECTIONMAP_CUBIC = false;
  77149. _this.REFLECTIONMAP_PROJECTION = false;
  77150. _this.REFLECTIONMAP_SKYBOX = false;
  77151. _this.REFLECTIONMAP_EXPLICIT = false;
  77152. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77153. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77154. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77155. _this.INVERTCUBICMAP = false;
  77156. _this.REFLECTIONMAP_OPPOSITEZ = false;
  77157. _this.LODINREFLECTIONALPHA = false;
  77158. _this.GAMMAREFLECTION = false;
  77159. // Default BJS.
  77160. _this.MAINUV1 = false;
  77161. _this.MAINUV2 = false;
  77162. _this.UV1 = false;
  77163. _this.UV2 = false;
  77164. _this.CLIPPLANE = false;
  77165. _this.POINTSIZE = false;
  77166. _this.FOG = false;
  77167. _this.NORMAL = false;
  77168. _this.NUM_BONE_INFLUENCERS = 0;
  77169. _this.BonesPerMesh = 0;
  77170. _this.INSTANCES = false;
  77171. _this.SHADOWFLOAT = false;
  77172. _this.rebuild();
  77173. return _this;
  77174. }
  77175. return BackgroundMaterialDefines;
  77176. }(BABYLON.MaterialDefines));
  77177. /**
  77178. * Background material used to create an efficient environement around your scene.
  77179. */
  77180. var BackgroundMaterial = /** @class */ (function (_super) {
  77181. __extends(BackgroundMaterial, _super);
  77182. /**
  77183. * constructor
  77184. * @param name The name of the material
  77185. * @param scene The scene to add the material to
  77186. */
  77187. function BackgroundMaterial(name, scene) {
  77188. var _this = _super.call(this, name, scene) || this;
  77189. _this.primaryColor = BABYLON.Color3.White();
  77190. _this.primaryLevel = 1;
  77191. _this.secondaryColor = BABYLON.Color3.Gray();
  77192. _this.secondaryLevel = 1;
  77193. _this.tertiaryColor = BABYLON.Color3.Black();
  77194. _this.tertiaryLevel = 1;
  77195. _this.reflectionTexture = null;
  77196. _this.reflectionBlur = 0;
  77197. _this.diffuseTexture = null;
  77198. /**
  77199. * Specify the list of lights casting shadow on the material.
  77200. * All scene shadow lights will be included if null.
  77201. */
  77202. _this._shadowLights = null;
  77203. _this.shadowLights = null;
  77204. _this.shadowBlurScale = 1;
  77205. _this.shadowLevel = 0;
  77206. _this.sceneCenter = BABYLON.Vector3.Zero();
  77207. _this.opacityFresnel = true;
  77208. _this.reflectionFresnel = false;
  77209. _this.reflectionFalloffDistance = 0.0;
  77210. _this.reflectionAmount = 1.0;
  77211. _this.reflectionReflectance0 = 0.05;
  77212. _this.reflectionReflectance90 = 0.5;
  77213. _this.useRGBColor = true;
  77214. _this.enableNoise = false;
  77215. /**
  77216. * Number of Simultaneous lights allowed on the material.
  77217. */
  77218. _this._maxSimultaneousLights = 4;
  77219. _this.maxSimultaneousLights = 4;
  77220. /**
  77221. * Keep track of the image processing observer to allow dispose and replace.
  77222. */
  77223. _this._imageProcessingObserver = null;
  77224. // Temp values kept as cache in the material.
  77225. _this._renderTargets = new BABYLON.SmartArray(16);
  77226. _this._reflectionControls = BABYLON.Vector4.Zero();
  77227. // Setup the default processing configuration to the scene.
  77228. _this._attachImageProcessingConfiguration(null);
  77229. _this.getRenderTargetTextures = function () {
  77230. _this._renderTargets.reset();
  77231. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  77232. _this._renderTargets.push(_this._diffuseTexture);
  77233. }
  77234. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  77235. _this._renderTargets.push(_this._reflectionTexture);
  77236. }
  77237. return _this._renderTargets;
  77238. };
  77239. return _this;
  77240. }
  77241. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  77242. /**
  77243. * Sets the reflection reflectance fresnel values according to the default standard
  77244. * empirically know to work well :-)
  77245. */
  77246. set: function (value) {
  77247. var reflectionWeight = value;
  77248. if (reflectionWeight < 0.5) {
  77249. reflectionWeight = reflectionWeight * 2.0;
  77250. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  77251. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  77252. }
  77253. else {
  77254. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  77255. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  77256. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  77257. }
  77258. },
  77259. enumerable: true,
  77260. configurable: true
  77261. });
  77262. /**
  77263. * Attaches a new image processing configuration to the PBR Material.
  77264. * @param configuration (if null the scene configuration will be use)
  77265. */
  77266. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  77267. var _this = this;
  77268. if (configuration === this._imageProcessingConfiguration) {
  77269. return;
  77270. }
  77271. // Detaches observer.
  77272. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77273. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77274. }
  77275. // Pick the scene configuration if needed.
  77276. if (!configuration) {
  77277. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  77278. }
  77279. else {
  77280. this._imageProcessingConfiguration = configuration;
  77281. }
  77282. // Attaches observer.
  77283. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77284. _this._markAllSubMeshesAsImageProcessingDirty();
  77285. });
  77286. };
  77287. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  77288. /**
  77289. * Gets the image processing configuration used either in this material.
  77290. */
  77291. get: function () {
  77292. return this._imageProcessingConfiguration;
  77293. },
  77294. /**
  77295. * Sets the Default image processing configuration used either in the this material.
  77296. *
  77297. * If sets to null, the scene one is in use.
  77298. */
  77299. set: function (value) {
  77300. this._attachImageProcessingConfiguration(value);
  77301. // Ensure the effect will be rebuilt.
  77302. this._markAllSubMeshesAsTexturesDirty();
  77303. },
  77304. enumerable: true,
  77305. configurable: true
  77306. });
  77307. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  77308. /**
  77309. * Gets wether the color curves effect is enabled.
  77310. */
  77311. get: function () {
  77312. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77313. },
  77314. /**
  77315. * Sets wether the color curves effect is enabled.
  77316. */
  77317. set: function (value) {
  77318. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77319. },
  77320. enumerable: true,
  77321. configurable: true
  77322. });
  77323. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  77324. /**
  77325. * Gets wether the color grading effect is enabled.
  77326. */
  77327. get: function () {
  77328. return this.imageProcessingConfiguration.colorGradingEnabled;
  77329. },
  77330. /**
  77331. * Gets wether the color grading effect is enabled.
  77332. */
  77333. set: function (value) {
  77334. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77335. },
  77336. enumerable: true,
  77337. configurable: true
  77338. });
  77339. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  77340. /**
  77341. * Gets wether tonemapping is enabled or not.
  77342. */
  77343. get: function () {
  77344. return this._imageProcessingConfiguration.toneMappingEnabled;
  77345. },
  77346. /**
  77347. * Sets wether tonemapping is enabled or not
  77348. */
  77349. set: function (value) {
  77350. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77351. },
  77352. enumerable: true,
  77353. configurable: true
  77354. });
  77355. ;
  77356. ;
  77357. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  77358. /**
  77359. * The camera exposure used on this material.
  77360. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77361. * This corresponds to a photographic exposure.
  77362. */
  77363. get: function () {
  77364. return this._imageProcessingConfiguration.exposure;
  77365. },
  77366. /**
  77367. * The camera exposure used on this material.
  77368. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77369. * This corresponds to a photographic exposure.
  77370. */
  77371. set: function (value) {
  77372. this._imageProcessingConfiguration.exposure = value;
  77373. },
  77374. enumerable: true,
  77375. configurable: true
  77376. });
  77377. ;
  77378. ;
  77379. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  77380. /**
  77381. * Gets The camera contrast used on this material.
  77382. */
  77383. get: function () {
  77384. return this._imageProcessingConfiguration.contrast;
  77385. },
  77386. /**
  77387. * Sets The camera contrast used on this material.
  77388. */
  77389. set: function (value) {
  77390. this._imageProcessingConfiguration.contrast = value;
  77391. },
  77392. enumerable: true,
  77393. configurable: true
  77394. });
  77395. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  77396. /**
  77397. * Gets the Color Grading 2D Lookup Texture.
  77398. */
  77399. get: function () {
  77400. return this._imageProcessingConfiguration.colorGradingTexture;
  77401. },
  77402. /**
  77403. * Sets the Color Grading 2D Lookup Texture.
  77404. */
  77405. set: function (value) {
  77406. this.imageProcessingConfiguration.colorGradingTexture = value;
  77407. },
  77408. enumerable: true,
  77409. configurable: true
  77410. });
  77411. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  77412. /**
  77413. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77414. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77415. * 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;
  77416. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77417. */
  77418. get: function () {
  77419. return this.imageProcessingConfiguration.colorCurves;
  77420. },
  77421. /**
  77422. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77423. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77424. * 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;
  77425. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77426. */
  77427. set: function (value) {
  77428. this.imageProcessingConfiguration.colorCurves = value;
  77429. },
  77430. enumerable: true,
  77431. configurable: true
  77432. });
  77433. /**
  77434. * The entire material has been created in order to prevent overdraw.
  77435. * @returns false
  77436. */
  77437. BackgroundMaterial.prototype.needAlphaTesting = function () {
  77438. return true;
  77439. };
  77440. /**
  77441. * The entire material has been created in order to prevent overdraw.
  77442. * @returns true if blending is enable
  77443. */
  77444. BackgroundMaterial.prototype.needAlphaBlending = function () {
  77445. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  77446. };
  77447. /**
  77448. * Checks wether the material is ready to be rendered for a given mesh.
  77449. * @param mesh The mesh to render
  77450. * @param subMesh The submesh to check against
  77451. * @param useInstances Specify wether or not the material is used with instances
  77452. */
  77453. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77454. var _this = this;
  77455. if (useInstances === void 0) { useInstances = false; }
  77456. if (subMesh.effect && this.isFrozen) {
  77457. if (this._wasPreviouslyReady) {
  77458. return true;
  77459. }
  77460. }
  77461. if (!subMesh._materialDefines) {
  77462. subMesh._materialDefines = new BackgroundMaterialDefines();
  77463. }
  77464. var scene = this.getScene();
  77465. var defines = subMesh._materialDefines;
  77466. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  77467. if (defines._renderId === scene.getRenderId()) {
  77468. return true;
  77469. }
  77470. }
  77471. var engine = scene.getEngine();
  77472. // Lights
  77473. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  77474. defines._needNormals = true;
  77475. // Textures
  77476. if (defines._areTexturesDirty) {
  77477. defines._needUVs = false;
  77478. if (scene.texturesEnabled) {
  77479. if (scene.getEngine().getCaps().textureLOD) {
  77480. defines.TEXTURELODSUPPORT = true;
  77481. }
  77482. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77483. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  77484. return false;
  77485. }
  77486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  77487. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  77488. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  77489. defines.OPACITYFRESNEL = this._opacityFresnel;
  77490. }
  77491. else {
  77492. defines.DIFFUSE = false;
  77493. defines.DIFFUSEHASALPHA = false;
  77494. defines.GAMMADIFFUSE = false;
  77495. defines.OPACITYFRESNEL = false;
  77496. }
  77497. var reflectionTexture = this._reflectionTexture;
  77498. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77499. if (!reflectionTexture.isReadyOrNotBlocking()) {
  77500. return false;
  77501. }
  77502. defines.REFLECTION = true;
  77503. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  77504. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  77505. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  77506. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  77507. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  77508. defines.INVERTCUBICMAP = true;
  77509. }
  77510. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  77511. switch (reflectionTexture.coordinatesMode) {
  77512. case BABYLON.Texture.CUBIC_MODE:
  77513. case BABYLON.Texture.INVCUBIC_MODE:
  77514. defines.REFLECTIONMAP_CUBIC = true;
  77515. break;
  77516. case BABYLON.Texture.EXPLICIT_MODE:
  77517. defines.REFLECTIONMAP_EXPLICIT = true;
  77518. break;
  77519. case BABYLON.Texture.PLANAR_MODE:
  77520. defines.REFLECTIONMAP_PLANAR = true;
  77521. break;
  77522. case BABYLON.Texture.PROJECTION_MODE:
  77523. defines.REFLECTIONMAP_PROJECTION = true;
  77524. break;
  77525. case BABYLON.Texture.SKYBOX_MODE:
  77526. defines.REFLECTIONMAP_SKYBOX = true;
  77527. break;
  77528. case BABYLON.Texture.SPHERICAL_MODE:
  77529. defines.REFLECTIONMAP_SPHERICAL = true;
  77530. break;
  77531. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  77532. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  77533. break;
  77534. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  77535. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  77536. break;
  77537. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  77538. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  77539. break;
  77540. }
  77541. if (this.reflectionFresnel) {
  77542. defines.REFLECTIONFRESNEL = true;
  77543. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  77544. this._reflectionControls.x = this.reflectionAmount;
  77545. this._reflectionControls.y = this.reflectionReflectance0;
  77546. this._reflectionControls.z = this.reflectionReflectance90;
  77547. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  77548. }
  77549. else {
  77550. defines.REFLECTIONFRESNEL = false;
  77551. defines.REFLECTIONFALLOFF = false;
  77552. }
  77553. }
  77554. else {
  77555. defines.REFLECTION = false;
  77556. defines.REFLECTIONFALLOFF = false;
  77557. defines.REFLECTIONBLUR = false;
  77558. defines.REFLECTIONMAP_3D = false;
  77559. defines.REFLECTIONMAP_SPHERICAL = false;
  77560. defines.REFLECTIONMAP_PLANAR = false;
  77561. defines.REFLECTIONMAP_CUBIC = false;
  77562. defines.REFLECTIONMAP_PROJECTION = false;
  77563. defines.REFLECTIONMAP_SKYBOX = false;
  77564. defines.REFLECTIONMAP_EXPLICIT = false;
  77565. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77566. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77567. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77568. defines.INVERTCUBICMAP = false;
  77569. defines.REFLECTIONMAP_OPPOSITEZ = false;
  77570. defines.LODINREFLECTIONALPHA = false;
  77571. defines.GAMMAREFLECTION = false;
  77572. }
  77573. }
  77574. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  77575. defines.USERGBCOLOR = this._useRGBColor;
  77576. defines.NOISE = this._enableNoise;
  77577. }
  77578. if (defines._areImageProcessingDirty) {
  77579. if (!this._imageProcessingConfiguration.isReady()) {
  77580. return false;
  77581. }
  77582. this._imageProcessingConfiguration.prepareDefines(defines);
  77583. }
  77584. // Misc.
  77585. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  77586. // Values that need to be evaluated on every frame
  77587. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  77588. // Attribs
  77589. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  77590. if (mesh) {
  77591. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77592. mesh.createNormals(true);
  77593. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  77594. }
  77595. }
  77596. }
  77597. // Get correct effect
  77598. if (defines.isDirty) {
  77599. defines.markAsProcessed();
  77600. scene.resetCachedMaterial();
  77601. // Fallbacks
  77602. var fallbacks = new BABYLON.EffectFallbacks();
  77603. if (defines.FOG) {
  77604. fallbacks.addFallback(0, "FOG");
  77605. }
  77606. if (defines.POINTSIZE) {
  77607. fallbacks.addFallback(1, "POINTSIZE");
  77608. }
  77609. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  77610. if (defines.NUM_BONE_INFLUENCERS > 0) {
  77611. fallbacks.addCPUSkinningFallback(0, mesh);
  77612. }
  77613. //Attributes
  77614. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77615. if (defines.NORMAL) {
  77616. attribs.push(BABYLON.VertexBuffer.NormalKind);
  77617. }
  77618. if (defines.UV1) {
  77619. attribs.push(BABYLON.VertexBuffer.UVKind);
  77620. }
  77621. if (defines.UV2) {
  77622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77623. }
  77624. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  77625. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  77626. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  77627. "vFogInfos", "vFogColor", "pointSize",
  77628. "vClipPlane", "mBones",
  77629. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  77630. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  77631. "shadowLevel", "alpha",
  77632. "vBackgroundCenter", "vReflectionControl",
  77633. "vDiffuseInfos", "diffuseMatrix",
  77634. ];
  77635. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  77636. var uniformBuffers = ["Material", "Scene"];
  77637. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  77638. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  77639. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  77640. uniformsNames: uniforms,
  77641. uniformBuffersNames: uniformBuffers,
  77642. samplers: samplers,
  77643. defines: defines,
  77644. maxSimultaneousLights: this._maxSimultaneousLights
  77645. });
  77646. var onCompiled = function (effect) {
  77647. if (_this.onCompiled) {
  77648. _this.onCompiled(effect);
  77649. }
  77650. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  77651. };
  77652. var join = defines.toString();
  77653. subMesh.setEffect(scene.getEngine().createEffect("background", {
  77654. attributes: attribs,
  77655. uniformsNames: uniforms,
  77656. uniformBuffersNames: uniformBuffers,
  77657. samplers: samplers,
  77658. defines: join,
  77659. fallbacks: fallbacks,
  77660. onCompiled: onCompiled,
  77661. onError: this.onError,
  77662. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  77663. }, engine), defines);
  77664. this.buildUniformLayout();
  77665. }
  77666. if (!subMesh.effect || !subMesh.effect.isReady()) {
  77667. return false;
  77668. }
  77669. defines._renderId = scene.getRenderId();
  77670. this._wasPreviouslyReady = true;
  77671. return true;
  77672. };
  77673. /**
  77674. * Build the uniform buffer used in the material.
  77675. */
  77676. BackgroundMaterial.prototype.buildUniformLayout = function () {
  77677. // Order is important !
  77678. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  77679. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  77680. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  77681. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  77682. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  77683. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  77684. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  77685. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  77686. this._uniformBuffer.addUniform("pointSize", 1);
  77687. this._uniformBuffer.addUniform("shadowLevel", 1);
  77688. this._uniformBuffer.addUniform("alpha", 1);
  77689. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  77690. this._uniformBuffer.addUniform("vReflectionControl", 4);
  77691. this._uniformBuffer.create();
  77692. };
  77693. /**
  77694. * Unbind the material.
  77695. */
  77696. BackgroundMaterial.prototype.unbind = function () {
  77697. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  77698. this._uniformBuffer.setTexture("diffuseSampler", null);
  77699. }
  77700. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  77701. this._uniformBuffer.setTexture("reflectionSampler", null);
  77702. }
  77703. _super.prototype.unbind.call(this);
  77704. };
  77705. /**
  77706. * Bind only the world matrix to the material.
  77707. * @param world The world matrix to bind.
  77708. */
  77709. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  77710. this._activeEffect.setMatrix("world", world);
  77711. };
  77712. /**
  77713. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  77714. * @param world The world matrix to bind.
  77715. * @param subMesh The submesh to bind for.
  77716. */
  77717. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  77718. var scene = this.getScene();
  77719. var defines = subMesh._materialDefines;
  77720. if (!defines) {
  77721. return;
  77722. }
  77723. var effect = subMesh.effect;
  77724. if (!effect) {
  77725. return;
  77726. }
  77727. this._activeEffect = effect;
  77728. // Matrices
  77729. this.bindOnlyWorldMatrix(world);
  77730. // Bones
  77731. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  77732. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  77733. if (mustRebind) {
  77734. this._uniformBuffer.bindToEffect(effect, "Material");
  77735. this.bindViewProjection(effect);
  77736. var reflectionTexture = this._reflectionTexture;
  77737. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  77738. // Texture uniforms
  77739. if (scene.texturesEnabled) {
  77740. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77741. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  77742. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  77743. }
  77744. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77745. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  77746. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  77747. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  77748. }
  77749. }
  77750. if (this.shadowLevel > 0) {
  77751. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  77752. }
  77753. this._uniformBuffer.updateFloat("alpha", this.alpha);
  77754. // Point size
  77755. if (this.pointsCloud) {
  77756. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  77757. }
  77758. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  77759. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  77760. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  77761. }
  77762. // Textures
  77763. if (scene.texturesEnabled) {
  77764. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77765. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  77766. }
  77767. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77768. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  77769. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  77770. }
  77771. else if (!defines.REFLECTIONBLUR) {
  77772. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  77773. }
  77774. else {
  77775. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  77776. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  77777. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  77778. }
  77779. if (defines.REFLECTIONFRESNEL) {
  77780. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  77781. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  77782. }
  77783. }
  77784. }
  77785. // Clip plane
  77786. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  77787. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  77788. }
  77789. if (mustRebind || !this.isFrozen) {
  77790. if (scene.lightsEnabled) {
  77791. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  77792. }
  77793. // View
  77794. this.bindView(effect);
  77795. // Fog
  77796. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  77797. // image processing
  77798. this._imageProcessingConfiguration.bind(this._activeEffect);
  77799. }
  77800. this._uniformBuffer.update();
  77801. this._afterBind(mesh);
  77802. };
  77803. /**
  77804. * Dispose the material.
  77805. * @forceDisposeEffect Force disposal of the associated effect.
  77806. * @forceDisposeTextures Force disposal of the associated textures.
  77807. */
  77808. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77809. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  77810. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  77811. if (forceDisposeTextures) {
  77812. if (this.diffuseTexture) {
  77813. this.diffuseTexture.dispose();
  77814. }
  77815. if (this.reflectionTexture) {
  77816. this.reflectionTexture.dispose();
  77817. }
  77818. }
  77819. this._renderTargets.dispose();
  77820. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77821. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77822. }
  77823. _super.prototype.dispose.call(this, forceDisposeEffect);
  77824. };
  77825. /**
  77826. * Clones the material.
  77827. * @name The cloned name.
  77828. * @returns The cloned material.
  77829. */
  77830. BackgroundMaterial.prototype.clone = function (name) {
  77831. var _this = this;
  77832. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  77833. };
  77834. /**
  77835. * Serializes the current material to its JSON representation.
  77836. * @returns The JSON representation.
  77837. */
  77838. BackgroundMaterial.prototype.serialize = function () {
  77839. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77840. serializationObject.customType = "BABYLON.BackgroundMaterial";
  77841. return serializationObject;
  77842. };
  77843. /**
  77844. * Gets the class name of the material
  77845. * @returns "BackgroundMaterial"
  77846. */
  77847. BackgroundMaterial.prototype.getClassName = function () {
  77848. return "BackgroundMaterial";
  77849. };
  77850. /**
  77851. * Parse a JSON input to create back a background material.
  77852. * @param source
  77853. * @param scene
  77854. * @param rootUrl
  77855. * @returns the instantiated BackgroundMaterial.
  77856. */
  77857. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  77858. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  77859. };
  77860. /**
  77861. * Standard reflectance value at parallel view angle.
  77862. */
  77863. BackgroundMaterial.standardReflectance0 = 0.05;
  77864. /**
  77865. * Standard reflectance value at grazing angle.
  77866. */
  77867. BackgroundMaterial.standardReflectance90 = 0.5;
  77868. __decorate([
  77869. BABYLON.serializeAsColor3()
  77870. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  77871. __decorate([
  77872. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77873. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  77874. __decorate([
  77875. BABYLON.serialize()
  77876. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  77877. __decorate([
  77878. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77879. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  77880. __decorate([
  77881. BABYLON.serializeAsColor3()
  77882. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  77883. __decorate([
  77884. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77885. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  77886. __decorate([
  77887. BABYLON.serialize()
  77888. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  77889. __decorate([
  77890. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77891. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  77892. __decorate([
  77893. BABYLON.serializeAsColor3()
  77894. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  77895. __decorate([
  77896. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77897. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  77898. __decorate([
  77899. BABYLON.serialize()
  77900. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  77901. __decorate([
  77902. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77903. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  77904. __decorate([
  77905. BABYLON.serializeAsTexture()
  77906. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  77907. __decorate([
  77908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77909. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  77910. __decorate([
  77911. BABYLON.serialize()
  77912. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  77913. __decorate([
  77914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77915. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  77916. __decorate([
  77917. BABYLON.serializeAsTexture()
  77918. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  77919. __decorate([
  77920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77921. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  77922. __decorate([
  77923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77924. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  77925. __decorate([
  77926. BABYLON.serialize()
  77927. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  77928. __decorate([
  77929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77930. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  77931. __decorate([
  77932. BABYLON.serialize()
  77933. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  77934. __decorate([
  77935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77936. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  77937. __decorate([
  77938. BABYLON.serializeAsVector3()
  77939. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  77940. __decorate([
  77941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77942. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  77943. __decorate([
  77944. BABYLON.serialize()
  77945. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  77946. __decorate([
  77947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77948. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  77949. __decorate([
  77950. BABYLON.serialize()
  77951. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  77952. __decorate([
  77953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77954. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  77955. __decorate([
  77956. BABYLON.serialize()
  77957. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  77958. __decorate([
  77959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77960. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  77961. __decorate([
  77962. BABYLON.serialize()
  77963. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  77964. __decorate([
  77965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77966. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  77967. __decorate([
  77968. BABYLON.serialize()
  77969. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  77970. __decorate([
  77971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77972. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  77973. __decorate([
  77974. BABYLON.serialize()
  77975. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  77976. __decorate([
  77977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77978. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  77979. __decorate([
  77980. BABYLON.serialize()
  77981. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  77982. __decorate([
  77983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77984. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  77985. __decorate([
  77986. BABYLON.serialize()
  77987. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  77988. __decorate([
  77989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77990. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  77991. __decorate([
  77992. BABYLON.serialize()
  77993. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  77994. __decorate([
  77995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77996. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  77997. __decorate([
  77998. BABYLON.serializeAsImageProcessingConfiguration()
  77999. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  78000. return BackgroundMaterial;
  78001. }(BABYLON.PushMaterial));
  78002. BABYLON.BackgroundMaterial = BackgroundMaterial;
  78003. })(BABYLON || (BABYLON = {}));
  78004. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  78005. var __assign = (this && this.__assign) || Object.assign || function(t) {
  78006. for (var s, i = 1, n = arguments.length; i < n; i++) {
  78007. s = arguments[i];
  78008. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  78009. t[p] = s[p];
  78010. }
  78011. return t;
  78012. };
  78013. var BABYLON;
  78014. (function (BABYLON) {
  78015. /**
  78016. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  78017. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  78018. * It also helps with the default setup of your imageProcessing configuration.
  78019. */
  78020. var EnvironmentHelper = /** @class */ (function () {
  78021. /**
  78022. * constructor
  78023. * @param options
  78024. * @param scene The scene to add the material to
  78025. */
  78026. function EnvironmentHelper(options, scene) {
  78027. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  78028. this._scene = scene;
  78029. this._setupBackground();
  78030. this._setupImageProcessing();
  78031. }
  78032. /**
  78033. * Creates the default options for the helper.
  78034. */
  78035. EnvironmentHelper._getDefaultOptions = function () {
  78036. return {
  78037. createGround: true,
  78038. groundSize: 15,
  78039. groundTexture: this._groundTextureCDNUrl,
  78040. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78041. groundOpacity: 0.9,
  78042. enableGroundShadow: true,
  78043. groundShadowLevel: 0.5,
  78044. enableGroundMirror: false,
  78045. groundMirrorSizeRatio: 0.3,
  78046. groundMirrorBlurKernel: 64,
  78047. groundMirrorAmount: 1,
  78048. groundMirrorFresnelWeight: 1,
  78049. groundMirrorFallOffDistance: 0,
  78050. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  78051. createSkybox: true,
  78052. skyboxSize: 20,
  78053. skyboxTexture: this._skyboxTextureCDNUrl,
  78054. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78055. backgroundYRotation: 0,
  78056. sizeAuto: true,
  78057. rootPosition: BABYLON.Vector3.Zero(),
  78058. setupImageProcessing: true,
  78059. environmentTexture: this._environmentTextureCDNUrl,
  78060. cameraExposure: 0.8,
  78061. cameraContrast: 1.2,
  78062. toneMappingEnabled: true,
  78063. };
  78064. };
  78065. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  78066. /**
  78067. * Gets the root mesh created by the helper.
  78068. */
  78069. get: function () {
  78070. return this._rootMesh;
  78071. },
  78072. enumerable: true,
  78073. configurable: true
  78074. });
  78075. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  78076. /**
  78077. * Gets the skybox created by the helper.
  78078. */
  78079. get: function () {
  78080. return this._skybox;
  78081. },
  78082. enumerable: true,
  78083. configurable: true
  78084. });
  78085. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  78086. /**
  78087. * Gets the skybox texture created by the helper.
  78088. */
  78089. get: function () {
  78090. return this._skyboxTexture;
  78091. },
  78092. enumerable: true,
  78093. configurable: true
  78094. });
  78095. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  78096. /**
  78097. * Gets the skybox material created by the helper.
  78098. */
  78099. get: function () {
  78100. return this._skyboxMaterial;
  78101. },
  78102. enumerable: true,
  78103. configurable: true
  78104. });
  78105. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  78106. /**
  78107. * Gets the ground mesh created by the helper.
  78108. */
  78109. get: function () {
  78110. return this._ground;
  78111. },
  78112. enumerable: true,
  78113. configurable: true
  78114. });
  78115. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  78116. /**
  78117. * Gets the ground texture created by the helper.
  78118. */
  78119. get: function () {
  78120. return this._groundTexture;
  78121. },
  78122. enumerable: true,
  78123. configurable: true
  78124. });
  78125. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  78126. /**
  78127. * Gets the ground mirror created by the helper.
  78128. */
  78129. get: function () {
  78130. return this._groundMirror;
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  78136. /**
  78137. * Gets the ground mirror render list to helps pushing the meshes
  78138. * you wish in the ground reflection.
  78139. */
  78140. get: function () {
  78141. if (this._groundMirror) {
  78142. return this._groundMirror.renderList;
  78143. }
  78144. return null;
  78145. },
  78146. enumerable: true,
  78147. configurable: true
  78148. });
  78149. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  78150. /**
  78151. * Gets the ground material created by the helper.
  78152. */
  78153. get: function () {
  78154. return this._groundMaterial;
  78155. },
  78156. enumerable: true,
  78157. configurable: true
  78158. });
  78159. /**
  78160. * Updates the background according to the new options
  78161. * @param options
  78162. */
  78163. EnvironmentHelper.prototype.updateOptions = function (options) {
  78164. var newOptions = __assign({}, this._options, options);
  78165. if (this._ground && !newOptions.createGround) {
  78166. this._ground.dispose();
  78167. this._ground = null;
  78168. }
  78169. if (this._groundMaterial && !newOptions.createGround) {
  78170. this._groundMaterial.dispose();
  78171. this._groundMaterial = null;
  78172. }
  78173. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  78174. this._groundTexture.dispose();
  78175. this._groundTexture = null;
  78176. }
  78177. if (this._skybox && !newOptions.createSkybox) {
  78178. this._skybox.dispose();
  78179. this._skybox = null;
  78180. }
  78181. if (this._skyboxMaterial && !newOptions.createSkybox) {
  78182. this._skyboxMaterial.dispose();
  78183. this._skyboxMaterial = null;
  78184. }
  78185. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  78186. this._skyboxTexture.dispose();
  78187. this._skyboxTexture = null;
  78188. }
  78189. if (this._groundMirror && !newOptions.enableGroundMirror) {
  78190. this._groundMirror.dispose();
  78191. this._groundMirror = null;
  78192. }
  78193. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  78194. this._scene.environmentTexture.dispose();
  78195. }
  78196. this._options = newOptions;
  78197. this._setupBackground();
  78198. this._setupImageProcessing();
  78199. };
  78200. /**
  78201. * Sets the primary color of all the available elements.
  78202. * @param color
  78203. */
  78204. EnvironmentHelper.prototype.setMainColor = function (color) {
  78205. if (this.groundMaterial) {
  78206. this.groundMaterial.primaryColor = color;
  78207. }
  78208. if (this.skyboxMaterial) {
  78209. this.skyboxMaterial.primaryColor = color;
  78210. }
  78211. if (this.groundMirror) {
  78212. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  78213. }
  78214. };
  78215. /**
  78216. * Setup the image processing according to the specified options.
  78217. */
  78218. EnvironmentHelper.prototype._setupImageProcessing = function () {
  78219. if (this._options.setupImageProcessing) {
  78220. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  78221. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  78222. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  78223. this._setupEnvironmentTexture();
  78224. }
  78225. };
  78226. /**
  78227. * Setup the environment texture according to the specified options.
  78228. */
  78229. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  78230. if (this._scene.environmentTexture) {
  78231. return;
  78232. }
  78233. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  78234. this._scene.environmentTexture = this._options.environmentTexture;
  78235. return;
  78236. }
  78237. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  78238. this._scene.environmentTexture = environmentTexture;
  78239. };
  78240. /**
  78241. * Setup the background according to the specified options.
  78242. */
  78243. EnvironmentHelper.prototype._setupBackground = function () {
  78244. if (!this._rootMesh) {
  78245. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  78246. }
  78247. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  78248. var sceneSize = this._getSceneSize();
  78249. if (this._options.createGround) {
  78250. this._setupGround(sceneSize);
  78251. this._setupGroundMaterial();
  78252. this._setupGroundDiffuseTexture();
  78253. if (this._options.enableGroundMirror) {
  78254. this._setupGroundMirrorTexture(sceneSize);
  78255. }
  78256. this._setupMirrorInGroundMaterial();
  78257. }
  78258. if (this._options.createSkybox) {
  78259. this._setupSkybox(sceneSize);
  78260. this._setupSkyboxMaterial();
  78261. this._setupSkyboxReflectionTexture();
  78262. }
  78263. this._rootMesh.position.x = sceneSize.rootPosition.x;
  78264. this._rootMesh.position.z = sceneSize.rootPosition.z;
  78265. this._rootMesh.position.y = sceneSize.rootPosition.y;
  78266. };
  78267. /**
  78268. * Get the scene sizes according to the setup.
  78269. */
  78270. EnvironmentHelper.prototype._getSceneSize = function () {
  78271. var groundSize = this._options.groundSize;
  78272. var skyboxSize = this._options.skyboxSize;
  78273. var rootPosition = this._options.rootPosition;
  78274. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  78275. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  78276. }
  78277. var sceneExtends = this._scene.getWorldExtends();
  78278. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  78279. var bias = 0.0001;
  78280. if (this._options.sizeAuto) {
  78281. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  78282. this._scene.activeCamera.upperRadiusLimit) {
  78283. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  78284. }
  78285. if (this._scene.activeCamera) {
  78286. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  78287. }
  78288. var sceneDiagonalLenght = sceneDiagonal.length();
  78289. if (sceneDiagonalLenght > groundSize) {
  78290. groundSize = sceneDiagonalLenght * 2;
  78291. }
  78292. // 10 % bigger.
  78293. groundSize *= 1.1;
  78294. skyboxSize *= 1.5;
  78295. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  78296. rootPosition.y = sceneExtends.min.y - bias;
  78297. }
  78298. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  78299. };
  78300. /**
  78301. * Setup the ground according to the specified options.
  78302. */
  78303. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  78304. var _this = this;
  78305. if (!this._ground) {
  78306. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  78307. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  78308. this._ground.parent = this._rootMesh;
  78309. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  78310. }
  78311. this._ground.receiveShadows = this._options.enableGroundShadow;
  78312. };
  78313. /**
  78314. * Setup the ground material according to the specified options.
  78315. */
  78316. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  78317. if (!this._groundMaterial) {
  78318. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  78319. }
  78320. this._groundMaterial.alpha = this._options.groundOpacity;
  78321. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  78322. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  78323. this._groundMaterial.primaryLevel = 1;
  78324. this._groundMaterial.primaryColor = this._options.groundColor;
  78325. this._groundMaterial.secondaryLevel = 0;
  78326. this._groundMaterial.tertiaryLevel = 0;
  78327. this._groundMaterial.useRGBColor = false;
  78328. this._groundMaterial.enableNoise = true;
  78329. if (this._ground) {
  78330. this._ground.material = this._groundMaterial;
  78331. }
  78332. };
  78333. /**
  78334. * Setup the ground diffuse texture according to the specified options.
  78335. */
  78336. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  78337. if (!this._groundMaterial) {
  78338. return;
  78339. }
  78340. if (this._groundTexture) {
  78341. return;
  78342. }
  78343. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  78344. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  78345. return;
  78346. }
  78347. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  78348. diffuseTexture.gammaSpace = false;
  78349. diffuseTexture.hasAlpha = true;
  78350. this._groundMaterial.diffuseTexture = diffuseTexture;
  78351. };
  78352. /**
  78353. * Setup the ground mirror texture according to the specified options.
  78354. */
  78355. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  78356. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78357. if (!this._groundMirror) {
  78358. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  78359. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  78360. this._groundMirror.anisotropicFilteringLevel = 1;
  78361. this._groundMirror.wrapU = wrapping;
  78362. this._groundMirror.wrapV = wrapping;
  78363. this._groundMirror.gammaSpace = false;
  78364. if (this._groundMirror.renderList) {
  78365. for (var i = 0; i < this._scene.meshes.length; i++) {
  78366. var mesh = this._scene.meshes[i];
  78367. if (mesh !== this._ground &&
  78368. mesh !== this._skybox &&
  78369. mesh !== this._rootMesh) {
  78370. this._groundMirror.renderList.push(mesh);
  78371. }
  78372. }
  78373. }
  78374. }
  78375. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  78376. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  78377. };
  78378. /**
  78379. * Setup the ground to receive the mirror texture.
  78380. */
  78381. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  78382. if (this._groundMaterial) {
  78383. this._groundMaterial.reflectionTexture = this._groundMirror;
  78384. this._groundMaterial.reflectionFresnel = true;
  78385. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  78386. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  78387. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  78388. }
  78389. };
  78390. /**
  78391. * Setup the skybox according to the specified options.
  78392. */
  78393. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  78394. var _this = this;
  78395. if (!this._skybox) {
  78396. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  78397. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  78398. }
  78399. this._skybox.parent = this._rootMesh;
  78400. };
  78401. /**
  78402. * Setup the skybox material according to the specified options.
  78403. */
  78404. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  78405. if (!this._skybox) {
  78406. return;
  78407. }
  78408. if (!this._skyboxMaterial) {
  78409. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  78410. }
  78411. this._skyboxMaterial.useRGBColor = false;
  78412. this._skyboxMaterial.primaryLevel = 1;
  78413. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  78414. this._skyboxMaterial.secondaryLevel = 0;
  78415. this._skyboxMaterial.tertiaryLevel = 0;
  78416. this._skyboxMaterial.enableNoise = true;
  78417. this._skybox.material = this._skyboxMaterial;
  78418. };
  78419. /**
  78420. * Setup the skybox reflection texture according to the specified options.
  78421. */
  78422. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  78423. if (!this._skyboxMaterial) {
  78424. return;
  78425. }
  78426. if (this._skyboxTexture) {
  78427. return;
  78428. }
  78429. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  78430. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78431. return;
  78432. }
  78433. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  78434. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  78435. this._skyboxTexture.gammaSpace = false;
  78436. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78437. };
  78438. /**
  78439. * Dispose all the elements created by the Helper.
  78440. */
  78441. EnvironmentHelper.prototype.dispose = function () {
  78442. if (this._groundMaterial) {
  78443. this._groundMaterial.dispose(true, true);
  78444. }
  78445. if (this._skyboxMaterial) {
  78446. this._skyboxMaterial.dispose(true, true);
  78447. }
  78448. this._rootMesh.dispose(false);
  78449. };
  78450. /**
  78451. * Default ground texture URL.
  78452. */
  78453. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  78454. /**
  78455. * Default skybox texture URL.
  78456. */
  78457. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  78458. /**
  78459. * Default environment texture URL.
  78460. */
  78461. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  78462. return EnvironmentHelper;
  78463. }());
  78464. BABYLON.EnvironmentHelper = EnvironmentHelper;
  78465. })(BABYLON || (BABYLON = {}));
  78466. //# sourceMappingURL=babylon.environmentHelper.js.map
  78467. 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}","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}"};
  78468. 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.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\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};"};
  78469. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  78470. var BABYLON;
  78471. (function (BABYLON) {
  78472. var GridMaterialDefines = /** @class */ (function (_super) {
  78473. __extends(GridMaterialDefines, _super);
  78474. function GridMaterialDefines() {
  78475. var _this = _super.call(this) || this;
  78476. _this.TRANSPARENT = false;
  78477. _this.FOG = false;
  78478. _this.PREMULTIPLYALPHA = false;
  78479. _this.rebuild();
  78480. return _this;
  78481. }
  78482. return GridMaterialDefines;
  78483. }(BABYLON.MaterialDefines));
  78484. /**
  78485. * The grid materials allows you to wrap any shape with a grid.
  78486. * Colors are customizable.
  78487. */
  78488. var GridMaterial = /** @class */ (function (_super) {
  78489. __extends(GridMaterial, _super);
  78490. /**
  78491. * constructor
  78492. * @param name The name given to the material in order to identify it afterwards.
  78493. * @param scene The scene the material is used in.
  78494. */
  78495. function GridMaterial(name, scene) {
  78496. var _this = _super.call(this, name, scene) || this;
  78497. /**
  78498. * Main color of the grid (e.g. between lines)
  78499. */
  78500. _this.mainColor = BABYLON.Color3.Black();
  78501. /**
  78502. * Color of the grid lines.
  78503. */
  78504. _this.lineColor = BABYLON.Color3.Teal();
  78505. /**
  78506. * The scale of the grid compared to unit.
  78507. */
  78508. _this.gridRatio = 1.0;
  78509. /**
  78510. * Allows setting an offset for the grid lines.
  78511. */
  78512. _this.gridOffset = BABYLON.Vector3.Zero();
  78513. /**
  78514. * The frequency of thicker lines.
  78515. */
  78516. _this.majorUnitFrequency = 10;
  78517. /**
  78518. * The visibility of minor units in the grid.
  78519. */
  78520. _this.minorUnitVisibility = 0.33;
  78521. /**
  78522. * The grid opacity outside of the lines.
  78523. */
  78524. _this.opacity = 1.0;
  78525. /**
  78526. * Determine RBG output is premultiplied by alpha value.
  78527. */
  78528. _this.preMultiplyAlpha = false;
  78529. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  78530. return _this;
  78531. }
  78532. /**
  78533. * Returns wehter or not the grid requires alpha blending.
  78534. */
  78535. GridMaterial.prototype.needAlphaBlending = function () {
  78536. return this.opacity < 1.0;
  78537. };
  78538. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  78539. return this.needAlphaBlending();
  78540. };
  78541. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78542. if (this.isFrozen) {
  78543. if (this._wasPreviouslyReady && subMesh.effect) {
  78544. return true;
  78545. }
  78546. }
  78547. if (!subMesh._materialDefines) {
  78548. subMesh._materialDefines = new GridMaterialDefines();
  78549. }
  78550. var defines = subMesh._materialDefines;
  78551. var scene = this.getScene();
  78552. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78553. if (this._renderId === scene.getRenderId()) {
  78554. return true;
  78555. }
  78556. }
  78557. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  78558. defines.TRANSPARENT = !defines.TRANSPARENT;
  78559. defines.markAsUnprocessed();
  78560. }
  78561. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  78562. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  78563. defines.markAsUnprocessed();
  78564. }
  78565. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  78566. // Get correct effect
  78567. if (defines.isDirty) {
  78568. defines.markAsProcessed();
  78569. scene.resetCachedMaterial();
  78570. // Attributes
  78571. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78572. // Defines
  78573. var join = defines.toString();
  78574. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  78575. }
  78576. if (!subMesh.effect || !subMesh.effect.isReady()) {
  78577. return false;
  78578. }
  78579. this._renderId = scene.getRenderId();
  78580. this._wasPreviouslyReady = true;
  78581. return true;
  78582. };
  78583. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  78584. var scene = this.getScene();
  78585. var defines = subMesh._materialDefines;
  78586. if (!defines) {
  78587. return;
  78588. }
  78589. var effect = subMesh.effect;
  78590. if (!effect) {
  78591. return;
  78592. }
  78593. this._activeEffect = effect;
  78594. // Matrices
  78595. this.bindOnlyWorldMatrix(world);
  78596. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  78597. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  78598. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  78599. // Uniforms
  78600. if (this._mustRebind(scene, effect)) {
  78601. this._activeEffect.setColor3("mainColor", this.mainColor);
  78602. this._activeEffect.setColor3("lineColor", this.lineColor);
  78603. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  78604. this._gridControl.x = this.gridRatio;
  78605. this._gridControl.y = Math.round(this.majorUnitFrequency);
  78606. this._gridControl.z = this.minorUnitVisibility;
  78607. this._gridControl.w = this.opacity;
  78608. this._activeEffect.setVector4("gridControl", this._gridControl);
  78609. }
  78610. // Fog
  78611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78612. this._afterBind(mesh, this._activeEffect);
  78613. };
  78614. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  78615. _super.prototype.dispose.call(this, forceDisposeEffect);
  78616. };
  78617. GridMaterial.prototype.clone = function (name) {
  78618. var _this = this;
  78619. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  78620. };
  78621. GridMaterial.prototype.serialize = function () {
  78622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78623. serializationObject.customType = "BABYLON.GridMaterial";
  78624. return serializationObject;
  78625. };
  78626. GridMaterial.prototype.getClassName = function () {
  78627. return "GridMaterial";
  78628. };
  78629. GridMaterial.Parse = function (source, scene, rootUrl) {
  78630. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  78631. };
  78632. __decorate([
  78633. BABYLON.serializeAsColor3()
  78634. ], GridMaterial.prototype, "mainColor", void 0);
  78635. __decorate([
  78636. BABYLON.serializeAsColor3()
  78637. ], GridMaterial.prototype, "lineColor", void 0);
  78638. __decorate([
  78639. BABYLON.serialize()
  78640. ], GridMaterial.prototype, "gridRatio", void 0);
  78641. __decorate([
  78642. BABYLON.serializeAsColor3()
  78643. ], GridMaterial.prototype, "gridOffset", void 0);
  78644. __decorate([
  78645. BABYLON.serialize()
  78646. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  78647. __decorate([
  78648. BABYLON.serialize()
  78649. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  78650. __decorate([
  78651. BABYLON.serialize()
  78652. ], GridMaterial.prototype, "opacity", void 0);
  78653. __decorate([
  78654. BABYLON.serialize()
  78655. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  78656. return GridMaterial;
  78657. }(BABYLON.PushMaterial));
  78658. BABYLON.GridMaterial = GridMaterial;
  78659. })(BABYLON || (BABYLON = {}));
  78660. //# sourceMappingURL=babylon.gridmaterial.js.map
  78661. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  78662. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  78663. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  78664. var BABYLON;
  78665. (function (BABYLON) {
  78666. var GLTFLoaderCoordinateSystemMode;
  78667. (function (GLTFLoaderCoordinateSystemMode) {
  78668. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  78669. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  78670. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  78671. // The glTF right-handed data is not transformed in any form and is loaded directly.
  78672. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  78673. // Sets the useRightHandedSystem flag on the scene.
  78674. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  78675. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  78676. var GLTFFileLoader = /** @class */ (function () {
  78677. function GLTFFileLoader() {
  78678. // V2 options
  78679. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  78680. this.compileMaterials = false;
  78681. this.compileShadowGenerators = false;
  78682. this.useClipPlane = false;
  78683. this.name = "gltf";
  78684. this.extensions = {
  78685. ".gltf": { isBinary: false },
  78686. ".glb": { isBinary: true }
  78687. };
  78688. }
  78689. GLTFFileLoader.prototype.dispose = function () {
  78690. if (this._loader) {
  78691. this._loader.dispose();
  78692. }
  78693. };
  78694. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78695. try {
  78696. var loaderData = GLTFFileLoader._parse(data);
  78697. if (this.onParsed) {
  78698. this.onParsed(loaderData);
  78699. }
  78700. this._loader = this._getLoader(loaderData);
  78701. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78702. }
  78703. catch (e) {
  78704. onError(e.message);
  78705. }
  78706. };
  78707. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78708. try {
  78709. var loaderData = GLTFFileLoader._parse(data);
  78710. if (this.onParsed) {
  78711. this.onParsed(loaderData);
  78712. }
  78713. this._loader = this._getLoader(loaderData);
  78714. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78715. }
  78716. catch (e) {
  78717. onError(e.message);
  78718. }
  78719. };
  78720. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  78721. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  78722. };
  78723. GLTFFileLoader.prototype.createPlugin = function () {
  78724. return new GLTFFileLoader();
  78725. };
  78726. GLTFFileLoader._parse = function (data) {
  78727. if (data instanceof ArrayBuffer) {
  78728. return GLTFFileLoader._parseBinary(data);
  78729. }
  78730. return {
  78731. json: JSON.parse(data),
  78732. bin: null
  78733. };
  78734. };
  78735. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  78736. var loaderVersion = { major: 2, minor: 0 };
  78737. var asset = loaderData.json.asset || {};
  78738. var version = GLTFFileLoader._parseVersion(asset.version);
  78739. if (!version) {
  78740. throw new Error("Invalid version: " + asset.version);
  78741. }
  78742. if (asset.minVersion !== undefined) {
  78743. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  78744. if (!minVersion) {
  78745. throw new Error("Invalid minimum version: " + asset.minVersion);
  78746. }
  78747. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  78748. throw new Error("Incompatible minimum version: " + asset.minVersion);
  78749. }
  78750. }
  78751. var createLoaders = {
  78752. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  78753. 2: GLTFFileLoader.CreateGLTFLoaderV2
  78754. };
  78755. var createLoader = createLoaders[version.major];
  78756. if (!createLoader) {
  78757. throw new Error("Unsupported version: " + asset.version);
  78758. }
  78759. return createLoader(this);
  78760. };
  78761. GLTFFileLoader._parseBinary = function (data) {
  78762. var Binary = {
  78763. Magic: 0x46546C67
  78764. };
  78765. var binaryReader = new BinaryReader(data);
  78766. var magic = binaryReader.readUint32();
  78767. if (magic !== Binary.Magic) {
  78768. throw new Error("Unexpected magic: " + magic);
  78769. }
  78770. var version = binaryReader.readUint32();
  78771. switch (version) {
  78772. case 1: return GLTFFileLoader._parseV1(binaryReader);
  78773. case 2: return GLTFFileLoader._parseV2(binaryReader);
  78774. }
  78775. throw new Error("Unsupported version: " + version);
  78776. };
  78777. GLTFFileLoader._parseV1 = function (binaryReader) {
  78778. var ContentFormat = {
  78779. JSON: 0
  78780. };
  78781. var length = binaryReader.readUint32();
  78782. if (length != binaryReader.getLength()) {
  78783. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  78784. }
  78785. var contentLength = binaryReader.readUint32();
  78786. var contentFormat = binaryReader.readUint32();
  78787. var content;
  78788. switch (contentFormat) {
  78789. case ContentFormat.JSON: {
  78790. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  78791. break;
  78792. }
  78793. default: {
  78794. throw new Error("Unexpected content format: " + contentFormat);
  78795. }
  78796. }
  78797. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  78798. var body = binaryReader.readUint8Array(bytesRemaining);
  78799. return {
  78800. json: content,
  78801. bin: body
  78802. };
  78803. };
  78804. GLTFFileLoader._parseV2 = function (binaryReader) {
  78805. var ChunkFormat = {
  78806. JSON: 0x4E4F534A,
  78807. BIN: 0x004E4942
  78808. };
  78809. var length = binaryReader.readUint32();
  78810. if (length !== binaryReader.getLength()) {
  78811. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  78812. }
  78813. // JSON chunk
  78814. var chunkLength = binaryReader.readUint32();
  78815. var chunkFormat = binaryReader.readUint32();
  78816. if (chunkFormat !== ChunkFormat.JSON) {
  78817. throw new Error("First chunk format is not JSON");
  78818. }
  78819. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  78820. // Look for BIN chunk
  78821. var bin = null;
  78822. while (binaryReader.getPosition() < binaryReader.getLength()) {
  78823. var chunkLength_1 = binaryReader.readUint32();
  78824. var chunkFormat_1 = binaryReader.readUint32();
  78825. switch (chunkFormat_1) {
  78826. case ChunkFormat.JSON: {
  78827. throw new Error("Unexpected JSON chunk");
  78828. }
  78829. case ChunkFormat.BIN: {
  78830. bin = binaryReader.readUint8Array(chunkLength_1);
  78831. break;
  78832. }
  78833. default: {
  78834. // ignore unrecognized chunkFormat
  78835. binaryReader.skipBytes(chunkLength_1);
  78836. break;
  78837. }
  78838. }
  78839. }
  78840. return {
  78841. json: json,
  78842. bin: bin
  78843. };
  78844. };
  78845. GLTFFileLoader._parseVersion = function (version) {
  78846. if (version === "1.0" || version === "1.0.1") {
  78847. return {
  78848. major: 1,
  78849. minor: 0
  78850. };
  78851. }
  78852. var match = (version + "").match(/^(\d+)\.(\d+)/);
  78853. if (!match) {
  78854. return null;
  78855. }
  78856. return {
  78857. major: parseInt(match[1]),
  78858. minor: parseInt(match[2])
  78859. };
  78860. };
  78861. GLTFFileLoader._compareVersion = function (a, b) {
  78862. if (a.major > b.major)
  78863. return 1;
  78864. if (a.major < b.major)
  78865. return -1;
  78866. if (a.minor > b.minor)
  78867. return 1;
  78868. if (a.minor < b.minor)
  78869. return -1;
  78870. return 0;
  78871. };
  78872. GLTFFileLoader._decodeBufferToText = function (buffer) {
  78873. var result = "";
  78874. var length = buffer.byteLength;
  78875. for (var i = 0; i < length; i++) {
  78876. result += String.fromCharCode(buffer[i]);
  78877. }
  78878. return result;
  78879. };
  78880. // V1 options
  78881. GLTFFileLoader.HomogeneousCoordinates = false;
  78882. GLTFFileLoader.IncrementalLoading = true;
  78883. return GLTFFileLoader;
  78884. }());
  78885. BABYLON.GLTFFileLoader = GLTFFileLoader;
  78886. var BinaryReader = /** @class */ (function () {
  78887. function BinaryReader(arrayBuffer) {
  78888. this._arrayBuffer = arrayBuffer;
  78889. this._dataView = new DataView(arrayBuffer);
  78890. this._byteOffset = 0;
  78891. }
  78892. BinaryReader.prototype.getPosition = function () {
  78893. return this._byteOffset;
  78894. };
  78895. BinaryReader.prototype.getLength = function () {
  78896. return this._arrayBuffer.byteLength;
  78897. };
  78898. BinaryReader.prototype.readUint32 = function () {
  78899. var value = this._dataView.getUint32(this._byteOffset, true);
  78900. this._byteOffset += 4;
  78901. return value;
  78902. };
  78903. BinaryReader.prototype.readUint8Array = function (length) {
  78904. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  78905. this._byteOffset += length;
  78906. return value;
  78907. };
  78908. BinaryReader.prototype.skipBytes = function (length) {
  78909. this._byteOffset += length;
  78910. };
  78911. return BinaryReader;
  78912. }());
  78913. if (BABYLON.SceneLoader) {
  78914. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  78915. }
  78916. })(BABYLON || (BABYLON = {}));
  78917. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  78918. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78919. var BABYLON;
  78920. (function (BABYLON) {
  78921. var GLTF1;
  78922. (function (GLTF1) {
  78923. /**
  78924. * Enums
  78925. */
  78926. var EComponentType;
  78927. (function (EComponentType) {
  78928. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78929. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78930. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78931. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78932. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78933. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  78934. var EShaderType;
  78935. (function (EShaderType) {
  78936. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  78937. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  78938. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  78939. var EParameterType;
  78940. (function (EParameterType) {
  78941. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  78942. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78943. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  78944. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78945. EParameterType[EParameterType["INT"] = 5124] = "INT";
  78946. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78947. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  78948. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  78949. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  78950. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  78951. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  78952. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  78953. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  78954. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  78955. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  78956. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  78957. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  78958. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  78959. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  78960. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  78961. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  78962. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  78963. var ETextureWrapMode;
  78964. (function (ETextureWrapMode) {
  78965. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78966. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78967. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78968. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  78969. var ETextureFilterType;
  78970. (function (ETextureFilterType) {
  78971. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  78972. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  78973. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78974. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78975. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78976. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78977. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  78978. var ETextureFormat;
  78979. (function (ETextureFormat) {
  78980. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  78981. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  78982. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  78983. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  78984. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  78985. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  78986. var ECullingType;
  78987. (function (ECullingType) {
  78988. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  78989. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  78990. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  78991. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  78992. var EBlendingFunction;
  78993. (function (EBlendingFunction) {
  78994. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  78995. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  78996. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  78997. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  78998. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  78999. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  79000. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  79001. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  79002. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  79003. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  79004. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  79005. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  79006. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  79007. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  79008. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  79009. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  79010. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79011. })(BABYLON || (BABYLON = {}));
  79012. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  79013. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79014. var BABYLON;
  79015. (function (BABYLON) {
  79016. var GLTF1;
  79017. (function (GLTF1) {
  79018. /**
  79019. * Tokenizer. Used for shaders compatibility
  79020. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  79021. */
  79022. var ETokenType;
  79023. (function (ETokenType) {
  79024. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  79025. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  79026. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  79027. })(ETokenType || (ETokenType = {}));
  79028. var Tokenizer = /** @class */ (function () {
  79029. function Tokenizer(toParse) {
  79030. this._pos = 0;
  79031. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  79032. this._toParse = toParse;
  79033. this._maxPos = toParse.length;
  79034. }
  79035. Tokenizer.prototype.getNextToken = function () {
  79036. if (this.isEnd())
  79037. return ETokenType.END_OF_INPUT;
  79038. this.currentString = this.read();
  79039. this.currentToken = ETokenType.UNKNOWN;
  79040. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  79041. this.currentToken = ETokenType.IDENTIFIER;
  79042. this.currentIdentifier = this.currentString;
  79043. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  79044. this.currentIdentifier += this.currentString;
  79045. this.forward();
  79046. }
  79047. }
  79048. return this.currentToken;
  79049. };
  79050. Tokenizer.prototype.peek = function () {
  79051. return this._toParse[this._pos];
  79052. };
  79053. Tokenizer.prototype.read = function () {
  79054. return this._toParse[this._pos++];
  79055. };
  79056. Tokenizer.prototype.forward = function () {
  79057. this._pos++;
  79058. };
  79059. Tokenizer.prototype.isEnd = function () {
  79060. return this._pos >= this._maxPos;
  79061. };
  79062. return Tokenizer;
  79063. }());
  79064. /**
  79065. * Values
  79066. */
  79067. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  79068. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  79069. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  79070. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  79071. /**
  79072. * Parse
  79073. */
  79074. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  79075. for (var buf in parsedBuffers) {
  79076. var parsedBuffer = parsedBuffers[buf];
  79077. gltfRuntime.buffers[buf] = parsedBuffer;
  79078. gltfRuntime.buffersCount++;
  79079. }
  79080. };
  79081. var parseShaders = function (parsedShaders, gltfRuntime) {
  79082. for (var sha in parsedShaders) {
  79083. var parsedShader = parsedShaders[sha];
  79084. gltfRuntime.shaders[sha] = parsedShader;
  79085. gltfRuntime.shaderscount++;
  79086. }
  79087. };
  79088. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  79089. for (var object in parsedObjects) {
  79090. var parsedObject = parsedObjects[object];
  79091. gltfRuntime[runtimeProperty][object] = parsedObject;
  79092. }
  79093. };
  79094. /**
  79095. * Utils
  79096. */
  79097. var normalizeUVs = function (buffer) {
  79098. if (!buffer) {
  79099. return;
  79100. }
  79101. for (var i = 0; i < buffer.length / 2; i++) {
  79102. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  79103. }
  79104. };
  79105. var getAttribute = function (attributeParameter) {
  79106. if (attributeParameter.semantic === "NORMAL") {
  79107. return "normal";
  79108. }
  79109. else if (attributeParameter.semantic === "POSITION") {
  79110. return "position";
  79111. }
  79112. else if (attributeParameter.semantic === "JOINT") {
  79113. return "matricesIndices";
  79114. }
  79115. else if (attributeParameter.semantic === "WEIGHT") {
  79116. return "matricesWeights";
  79117. }
  79118. else if (attributeParameter.semantic === "COLOR") {
  79119. return "color";
  79120. }
  79121. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  79122. var channel = Number(attributeParameter.semantic.split("_")[1]);
  79123. return "uv" + (channel === 0 ? "" : channel + 1);
  79124. }
  79125. return null;
  79126. };
  79127. /**
  79128. * Loads and creates animations
  79129. */
  79130. var loadAnimations = function (gltfRuntime) {
  79131. for (var anim in gltfRuntime.animations) {
  79132. var animation = gltfRuntime.animations[anim];
  79133. if (!animation.channels || !animation.samplers) {
  79134. continue;
  79135. }
  79136. var lastAnimation = null;
  79137. for (var i = 0; i < animation.channels.length; i++) {
  79138. // Get parameters and load buffers
  79139. var channel = animation.channels[i];
  79140. var sampler = animation.samplers[channel.sampler];
  79141. if (!sampler) {
  79142. continue;
  79143. }
  79144. var inputData = null;
  79145. var outputData = null;
  79146. if (animation.parameters) {
  79147. inputData = animation.parameters[sampler.input];
  79148. outputData = animation.parameters[sampler.output];
  79149. }
  79150. else {
  79151. inputData = sampler.input;
  79152. outputData = sampler.output;
  79153. }
  79154. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  79155. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  79156. var targetID = channel.target.id;
  79157. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  79158. if (targetNode === null) {
  79159. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  79160. }
  79161. if (targetNode === null) {
  79162. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  79163. continue;
  79164. }
  79165. var isBone = targetNode instanceof BABYLON.Bone;
  79166. // Get target path (position, rotation or scaling)
  79167. var targetPath = channel.target.path;
  79168. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  79169. if (targetPathIndex !== -1) {
  79170. targetPath = babylonAnimationPaths[targetPathIndex];
  79171. }
  79172. // Determine animation type
  79173. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  79174. if (!isBone) {
  79175. if (targetPath === "rotationQuaternion") {
  79176. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79177. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  79178. }
  79179. else {
  79180. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79181. }
  79182. }
  79183. // Create animation and key frames
  79184. var babylonAnimation = null;
  79185. var keys = [];
  79186. var arrayOffset = 0;
  79187. var modifyKey = false;
  79188. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  79189. babylonAnimation = lastAnimation;
  79190. modifyKey = true;
  79191. }
  79192. if (!modifyKey) {
  79193. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79194. }
  79195. // For each frame
  79196. for (var j = 0; j < bufferInput.length; j++) {
  79197. var value = null;
  79198. if (targetPath === "rotationQuaternion") {
  79199. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  79200. arrayOffset += 4;
  79201. }
  79202. else {
  79203. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  79204. arrayOffset += 3;
  79205. }
  79206. if (isBone) {
  79207. var bone = targetNode;
  79208. var translation = BABYLON.Vector3.Zero();
  79209. var rotationQuaternion = new BABYLON.Quaternion();
  79210. var scaling = BABYLON.Vector3.Zero();
  79211. // Warning on decompose
  79212. var mat = bone.getBaseMatrix();
  79213. if (modifyKey && lastAnimation) {
  79214. mat = lastAnimation.getKeys()[j].value;
  79215. }
  79216. mat.decompose(scaling, rotationQuaternion, translation);
  79217. if (targetPath === "position") {
  79218. translation = value;
  79219. }
  79220. else if (targetPath === "rotationQuaternion") {
  79221. rotationQuaternion = value;
  79222. }
  79223. else {
  79224. scaling = value;
  79225. }
  79226. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  79227. }
  79228. if (!modifyKey) {
  79229. keys.push({
  79230. frame: bufferInput[j],
  79231. value: value
  79232. });
  79233. }
  79234. else if (lastAnimation) {
  79235. lastAnimation.getKeys()[j].value = value;
  79236. }
  79237. }
  79238. // Finish
  79239. if (!modifyKey && babylonAnimation) {
  79240. babylonAnimation.setKeys(keys);
  79241. targetNode.animations.push(babylonAnimation);
  79242. }
  79243. lastAnimation = babylonAnimation;
  79244. gltfRuntime.scene.stopAnimation(targetNode);
  79245. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  79246. }
  79247. }
  79248. };
  79249. /**
  79250. * Returns the bones transformation matrix
  79251. */
  79252. var configureBoneTransformation = function (node) {
  79253. var mat = null;
  79254. if (node.translation || node.rotation || node.scale) {
  79255. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  79256. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  79257. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  79258. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  79259. }
  79260. else {
  79261. mat = BABYLON.Matrix.FromArray(node.matrix);
  79262. }
  79263. return mat;
  79264. };
  79265. /**
  79266. * Returns the parent bone
  79267. */
  79268. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  79269. // Try to find
  79270. for (var i = 0; i < newSkeleton.bones.length; i++) {
  79271. if (newSkeleton.bones[i].name === jointName) {
  79272. return newSkeleton.bones[i];
  79273. }
  79274. }
  79275. // Not found, search in gltf nodes
  79276. var nodes = gltfRuntime.nodes;
  79277. for (var nde in nodes) {
  79278. var node = nodes[nde];
  79279. if (!node.jointName) {
  79280. continue;
  79281. }
  79282. var children = node.children;
  79283. for (var i = 0; i < children.length; i++) {
  79284. var child = gltfRuntime.nodes[children[i]];
  79285. if (!child.jointName) {
  79286. continue;
  79287. }
  79288. if (child.jointName === jointName) {
  79289. var mat = configureBoneTransformation(node);
  79290. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  79291. bone.id = nde;
  79292. return bone;
  79293. }
  79294. }
  79295. }
  79296. return null;
  79297. };
  79298. /**
  79299. * Returns the appropriate root node
  79300. */
  79301. var getNodeToRoot = function (nodesToRoot, id) {
  79302. for (var i = 0; i < nodesToRoot.length; i++) {
  79303. var nodeToRoot = nodesToRoot[i];
  79304. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  79305. var child = nodeToRoot.node.children[j];
  79306. if (child === id) {
  79307. return nodeToRoot.bone;
  79308. }
  79309. }
  79310. }
  79311. return null;
  79312. };
  79313. /**
  79314. * Returns the node with the joint name
  79315. */
  79316. var getJointNode = function (gltfRuntime, jointName) {
  79317. var nodes = gltfRuntime.nodes;
  79318. var node = nodes[jointName];
  79319. if (node) {
  79320. return {
  79321. node: node,
  79322. id: jointName
  79323. };
  79324. }
  79325. for (var nde in nodes) {
  79326. node = nodes[nde];
  79327. if (node.jointName === jointName) {
  79328. return {
  79329. node: node,
  79330. id: nde
  79331. };
  79332. }
  79333. }
  79334. return null;
  79335. };
  79336. /**
  79337. * Checks if a nodes is in joints
  79338. */
  79339. var nodeIsInJoints = function (skins, id) {
  79340. for (var i = 0; i < skins.jointNames.length; i++) {
  79341. if (skins.jointNames[i] === id) {
  79342. return true;
  79343. }
  79344. }
  79345. return false;
  79346. };
  79347. /**
  79348. * Fills the nodes to root for bones and builds hierarchy
  79349. */
  79350. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  79351. // Creates nodes for root
  79352. for (var nde in gltfRuntime.nodes) {
  79353. var node = gltfRuntime.nodes[nde];
  79354. var id = nde;
  79355. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  79356. continue;
  79357. }
  79358. // Create node to root bone
  79359. var mat = configureBoneTransformation(node);
  79360. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  79361. bone.id = id;
  79362. nodesToRoot.push({ bone: bone, node: node, id: id });
  79363. }
  79364. // Parenting
  79365. for (var i = 0; i < nodesToRoot.length; i++) {
  79366. var nodeToRoot = nodesToRoot[i];
  79367. var children = nodeToRoot.node.children;
  79368. for (var j = 0; j < children.length; j++) {
  79369. var child = null;
  79370. for (var k = 0; k < nodesToRoot.length; k++) {
  79371. if (nodesToRoot[k].id === children[j]) {
  79372. child = nodesToRoot[k];
  79373. break;
  79374. }
  79375. }
  79376. if (child) {
  79377. child.bone._parent = nodeToRoot.bone;
  79378. nodeToRoot.bone.children.push(child.bone);
  79379. }
  79380. }
  79381. }
  79382. };
  79383. /**
  79384. * Imports a skeleton
  79385. */
  79386. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  79387. if (!newSkeleton) {
  79388. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  79389. }
  79390. if (!skins.babylonSkeleton) {
  79391. return newSkeleton;
  79392. }
  79393. // Find the root bones
  79394. var nodesToRoot = [];
  79395. var nodesToRootToAdd = [];
  79396. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  79397. newSkeleton.bones = [];
  79398. // Joints
  79399. for (var i = 0; i < skins.jointNames.length; i++) {
  79400. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  79401. if (!jointNode) {
  79402. continue;
  79403. }
  79404. var node = jointNode.node;
  79405. if (!node) {
  79406. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  79407. continue;
  79408. }
  79409. var id = jointNode.id;
  79410. // Optimize, if the bone already exists...
  79411. var existingBone = gltfRuntime.scene.getBoneByID(id);
  79412. if (existingBone) {
  79413. newSkeleton.bones.push(existingBone);
  79414. continue;
  79415. }
  79416. // Search for parent bone
  79417. var foundBone = false;
  79418. var parentBone = null;
  79419. for (var j = 0; j < i; j++) {
  79420. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  79421. if (!jointNode_1) {
  79422. continue;
  79423. }
  79424. var joint = jointNode_1.node;
  79425. if (!joint) {
  79426. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  79427. continue;
  79428. }
  79429. var children = joint.children;
  79430. if (!children) {
  79431. continue;
  79432. }
  79433. foundBone = false;
  79434. for (var k = 0; k < children.length; k++) {
  79435. if (children[k] === id) {
  79436. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  79437. foundBone = true;
  79438. break;
  79439. }
  79440. }
  79441. if (foundBone) {
  79442. break;
  79443. }
  79444. }
  79445. // Create bone
  79446. var mat = configureBoneTransformation(node);
  79447. if (!parentBone && nodesToRoot.length > 0) {
  79448. parentBone = getNodeToRoot(nodesToRoot, id);
  79449. if (parentBone) {
  79450. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  79451. nodesToRootToAdd.push(parentBone);
  79452. }
  79453. }
  79454. }
  79455. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  79456. bone.id = id;
  79457. }
  79458. // Polish
  79459. var bones = newSkeleton.bones;
  79460. newSkeleton.bones = [];
  79461. for (var i = 0; i < skins.jointNames.length; i++) {
  79462. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  79463. if (!jointNode) {
  79464. continue;
  79465. }
  79466. for (var j = 0; j < bones.length; j++) {
  79467. if (bones[j].id === jointNode.id) {
  79468. newSkeleton.bones.push(bones[j]);
  79469. break;
  79470. }
  79471. }
  79472. }
  79473. newSkeleton.prepare();
  79474. // Finish
  79475. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  79476. newSkeleton.bones.push(nodesToRootToAdd[i]);
  79477. }
  79478. return newSkeleton;
  79479. };
  79480. /**
  79481. * Imports a mesh and its geometries
  79482. */
  79483. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  79484. if (!newMesh) {
  79485. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  79486. newMesh.id = id;
  79487. }
  79488. if (!node.babylonNode) {
  79489. return newMesh;
  79490. }
  79491. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  79492. if (!newMesh.material) {
  79493. newMesh.material = multiMat;
  79494. }
  79495. var vertexData = new BABYLON.VertexData();
  79496. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  79497. var verticesStarts = new Array();
  79498. var verticesCounts = new Array();
  79499. var indexStarts = new Array();
  79500. var indexCounts = new Array();
  79501. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79502. var meshID = meshes[meshIndex];
  79503. var mesh = gltfRuntime.meshes[meshID];
  79504. if (!mesh) {
  79505. continue;
  79506. }
  79507. // Positions, normals and UVs
  79508. for (var i = 0; i < mesh.primitives.length; i++) {
  79509. // Temporary vertex data
  79510. var tempVertexData = new BABYLON.VertexData();
  79511. var primitive = mesh.primitives[i];
  79512. if (primitive.mode !== 4) {
  79513. // continue;
  79514. }
  79515. var attributes = primitive.attributes;
  79516. var accessor = null;
  79517. var buffer = null;
  79518. // Set positions, normal and uvs
  79519. for (var semantic in attributes) {
  79520. // Link accessor and buffer view
  79521. accessor = gltfRuntime.accessors[attributes[semantic]];
  79522. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79523. if (semantic === "NORMAL") {
  79524. tempVertexData.normals = new Float32Array(buffer.length);
  79525. tempVertexData.normals.set(buffer);
  79526. }
  79527. else if (semantic === "POSITION") {
  79528. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  79529. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  79530. for (var j = 0; j < buffer.length; j += 4) {
  79531. tempVertexData.positions[j] = buffer[j];
  79532. tempVertexData.positions[j + 1] = buffer[j + 1];
  79533. tempVertexData.positions[j + 2] = buffer[j + 2];
  79534. }
  79535. }
  79536. else {
  79537. tempVertexData.positions = new Float32Array(buffer.length);
  79538. tempVertexData.positions.set(buffer);
  79539. }
  79540. verticesCounts.push(tempVertexData.positions.length);
  79541. }
  79542. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  79543. var channel = Number(semantic.split("_")[1]);
  79544. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  79545. var uvs = new Float32Array(buffer.length);
  79546. uvs.set(buffer);
  79547. normalizeUVs(uvs);
  79548. tempVertexData.set(uvs, uvKind);
  79549. }
  79550. else if (semantic === "JOINT") {
  79551. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  79552. tempVertexData.matricesIndices.set(buffer);
  79553. }
  79554. else if (semantic === "WEIGHT") {
  79555. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  79556. tempVertexData.matricesWeights.set(buffer);
  79557. }
  79558. else if (semantic === "COLOR") {
  79559. tempVertexData.colors = new Float32Array(buffer.length);
  79560. tempVertexData.colors.set(buffer);
  79561. }
  79562. }
  79563. // Indices
  79564. accessor = gltfRuntime.accessors[primitive.indices];
  79565. if (accessor) {
  79566. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79567. tempVertexData.indices = new Int32Array(buffer.length);
  79568. tempVertexData.indices.set(buffer);
  79569. indexCounts.push(tempVertexData.indices.length);
  79570. }
  79571. else {
  79572. // Set indices on the fly
  79573. var indices = [];
  79574. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  79575. indices.push(j);
  79576. }
  79577. tempVertexData.indices = new Int32Array(indices);
  79578. indexCounts.push(tempVertexData.indices.length);
  79579. }
  79580. vertexData.merge(tempVertexData);
  79581. // Sub material
  79582. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  79583. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  79584. // Update vertices start and index start
  79585. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  79586. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  79587. }
  79588. }
  79589. // Apply geometry
  79590. geometry.setAllVerticesData(vertexData, false);
  79591. newMesh.computeWorldMatrix(true);
  79592. // Apply submeshes
  79593. newMesh.subMeshes = [];
  79594. var index = 0;
  79595. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79596. var meshID = meshes[meshIndex];
  79597. var mesh = gltfRuntime.meshes[meshID];
  79598. if (!mesh) {
  79599. continue;
  79600. }
  79601. for (var i = 0; i < mesh.primitives.length; i++) {
  79602. if (mesh.primitives[i].mode !== 4) {
  79603. //continue;
  79604. }
  79605. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  79606. index++;
  79607. }
  79608. }
  79609. // Finish
  79610. return newMesh;
  79611. };
  79612. /**
  79613. * Configure node transformation from position, rotation and scaling
  79614. */
  79615. var configureNode = function (newNode, position, rotation, scaling) {
  79616. if (newNode.position) {
  79617. newNode.position = position;
  79618. }
  79619. if (newNode.rotationQuaternion || newNode.rotation) {
  79620. newNode.rotationQuaternion = rotation;
  79621. }
  79622. if (newNode.scaling) {
  79623. newNode.scaling = scaling;
  79624. }
  79625. };
  79626. /**
  79627. * Configures node from transformation matrix
  79628. */
  79629. var configureNodeFromMatrix = function (newNode, node, parent) {
  79630. if (node.matrix) {
  79631. var position = new BABYLON.Vector3(0, 0, 0);
  79632. var rotation = new BABYLON.Quaternion();
  79633. var scaling = new BABYLON.Vector3(0, 0, 0);
  79634. var mat = BABYLON.Matrix.FromArray(node.matrix);
  79635. mat.decompose(scaling, rotation, position);
  79636. configureNode(newNode, position, rotation, scaling);
  79637. }
  79638. else if (node.translation && node.rotation && node.scale) {
  79639. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  79640. }
  79641. newNode.computeWorldMatrix(true);
  79642. };
  79643. /**
  79644. * Imports a node
  79645. */
  79646. var importNode = function (gltfRuntime, node, id, parent) {
  79647. var lastNode = null;
  79648. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  79649. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  79650. return null;
  79651. }
  79652. }
  79653. // Meshes
  79654. if (node.skin) {
  79655. if (node.meshes) {
  79656. var skin = gltfRuntime.skins[node.skin];
  79657. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  79658. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  79659. if (newMesh.skeleton === null) {
  79660. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  79661. if (!skin.babylonSkeleton) {
  79662. skin.babylonSkeleton = newMesh.skeleton;
  79663. }
  79664. }
  79665. lastNode = newMesh;
  79666. }
  79667. }
  79668. else if (node.meshes) {
  79669. /**
  79670. * Improve meshes property
  79671. */
  79672. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  79673. lastNode = newMesh;
  79674. }
  79675. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  79676. var light = gltfRuntime.lights[node.light];
  79677. if (light) {
  79678. if (light.type === "ambient") {
  79679. var ambienLight = light[light.type];
  79680. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79681. hemiLight.name = node.name || "";
  79682. if (ambienLight.color) {
  79683. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  79684. }
  79685. lastNode = hemiLight;
  79686. }
  79687. else if (light.type === "directional") {
  79688. var directionalLight = light[light.type];
  79689. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79690. dirLight.name = node.name || "";
  79691. if (directionalLight.color) {
  79692. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  79693. }
  79694. lastNode = dirLight;
  79695. }
  79696. else if (light.type === "point") {
  79697. var pointLight = light[light.type];
  79698. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79699. ptLight.name = node.name || "";
  79700. if (pointLight.color) {
  79701. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  79702. }
  79703. lastNode = ptLight;
  79704. }
  79705. else if (light.type === "spot") {
  79706. var spotLight = light[light.type];
  79707. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  79708. spLight.name = node.name || "";
  79709. if (spotLight.color) {
  79710. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  79711. }
  79712. if (spotLight.fallOfAngle) {
  79713. spLight.angle = spotLight.fallOfAngle;
  79714. }
  79715. if (spotLight.fallOffExponent) {
  79716. spLight.exponent = spotLight.fallOffExponent;
  79717. }
  79718. lastNode = spLight;
  79719. }
  79720. }
  79721. }
  79722. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  79723. var camera = gltfRuntime.cameras[node.camera];
  79724. if (camera) {
  79725. if (camera.type === "orthographic") {
  79726. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79727. orthoCamera.name = node.name || "";
  79728. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  79729. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  79730. lastNode = orthoCamera;
  79731. }
  79732. else if (camera.type === "perspective") {
  79733. var perspectiveCamera = camera[camera.type];
  79734. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79735. persCamera.name = node.name || "";
  79736. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  79737. if (!perspectiveCamera.aspectRatio) {
  79738. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  79739. }
  79740. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  79741. persCamera.maxZ = perspectiveCamera.zfar;
  79742. persCamera.minZ = perspectiveCamera.znear;
  79743. }
  79744. lastNode = persCamera;
  79745. }
  79746. }
  79747. }
  79748. // Empty node
  79749. if (!node.jointName) {
  79750. if (node.babylonNode) {
  79751. return node.babylonNode;
  79752. }
  79753. else if (lastNode === null) {
  79754. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  79755. node.babylonNode = dummy;
  79756. lastNode = dummy;
  79757. }
  79758. }
  79759. if (lastNode !== null) {
  79760. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  79761. configureNodeFromMatrix(lastNode, node, parent);
  79762. }
  79763. else {
  79764. var translation = node.translation || [0, 0, 0];
  79765. var rotation = node.rotation || [0, 0, 0, 1];
  79766. var scale = node.scale || [1, 1, 1];
  79767. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  79768. }
  79769. lastNode.updateCache(true);
  79770. node.babylonNode = lastNode;
  79771. }
  79772. return lastNode;
  79773. };
  79774. /**
  79775. * Traverses nodes and creates them
  79776. */
  79777. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  79778. if (meshIncluded === void 0) { meshIncluded = false; }
  79779. var node = gltfRuntime.nodes[id];
  79780. var newNode = null;
  79781. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  79782. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  79783. meshIncluded = true;
  79784. }
  79785. else {
  79786. meshIncluded = false;
  79787. }
  79788. }
  79789. else {
  79790. meshIncluded = true;
  79791. }
  79792. if (!node.jointName && meshIncluded) {
  79793. newNode = importNode(gltfRuntime, node, id, parent);
  79794. if (newNode !== null) {
  79795. newNode.id = id;
  79796. newNode.parent = parent;
  79797. }
  79798. }
  79799. if (node.children) {
  79800. for (var i = 0; i < node.children.length; i++) {
  79801. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  79802. }
  79803. }
  79804. };
  79805. /**
  79806. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  79807. */
  79808. var postLoad = function (gltfRuntime) {
  79809. // Nodes
  79810. var currentScene = gltfRuntime.currentScene;
  79811. if (currentScene) {
  79812. for (var i = 0; i < currentScene.nodes.length; i++) {
  79813. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79814. }
  79815. }
  79816. else {
  79817. for (var thing in gltfRuntime.scenes) {
  79818. currentScene = gltfRuntime.scenes[thing];
  79819. for (var i = 0; i < currentScene.nodes.length; i++) {
  79820. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79821. }
  79822. }
  79823. }
  79824. // Set animations
  79825. loadAnimations(gltfRuntime);
  79826. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  79827. var skeleton = gltfRuntime.scene.skeletons[i];
  79828. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  79829. }
  79830. };
  79831. /**
  79832. * onBind shaderrs callback to set uniforms and matrices
  79833. */
  79834. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  79835. var materialValues = material.values || technique.parameters;
  79836. for (var unif in unTreatedUniforms) {
  79837. var uniform = unTreatedUniforms[unif];
  79838. var type = uniform.type;
  79839. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  79840. if (uniform.semantic && !uniform.source && !uniform.node) {
  79841. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  79842. }
  79843. else if (uniform.semantic && (uniform.source || uniform.node)) {
  79844. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  79845. if (source === null) {
  79846. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  79847. }
  79848. if (source === null) {
  79849. continue;
  79850. }
  79851. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  79852. }
  79853. }
  79854. else {
  79855. var value = materialValues[technique.uniforms[unif]];
  79856. if (!value) {
  79857. continue;
  79858. }
  79859. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  79860. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  79861. if (texture === null || texture === undefined) {
  79862. continue;
  79863. }
  79864. shaderMaterial.getEffect().setTexture(unif, texture);
  79865. }
  79866. else {
  79867. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  79868. }
  79869. }
  79870. }
  79871. onSuccess(shaderMaterial);
  79872. };
  79873. /**
  79874. * Prepare uniforms to send the only one time
  79875. * Loads the appropriate textures
  79876. */
  79877. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  79878. var materialValues = material.values || technique.parameters;
  79879. var techniqueUniforms = technique.uniforms;
  79880. /**
  79881. * Prepare values here (not matrices)
  79882. */
  79883. for (var unif in unTreatedUniforms) {
  79884. var uniform = unTreatedUniforms[unif];
  79885. var type = uniform.type;
  79886. var value = materialValues[techniqueUniforms[unif]];
  79887. if (value === undefined) {
  79888. // In case the value is the same for all materials
  79889. value = uniform.value;
  79890. }
  79891. if (!value) {
  79892. continue;
  79893. }
  79894. var onLoadTexture = function (uniformName) {
  79895. return function (texture) {
  79896. if (uniform.value && uniformName) {
  79897. // Static uniform
  79898. shaderMaterial.setTexture(uniformName, texture);
  79899. delete unTreatedUniforms[uniformName];
  79900. }
  79901. };
  79902. };
  79903. // Texture (sampler2D)
  79904. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  79905. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  79906. }
  79907. else {
  79908. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  79909. // Static uniform
  79910. delete unTreatedUniforms[unif];
  79911. }
  79912. }
  79913. }
  79914. };
  79915. /**
  79916. * Shader compilation failed
  79917. */
  79918. var onShaderCompileError = function (program, shaderMaterial, onError) {
  79919. return function (effect, error) {
  79920. shaderMaterial.dispose(true);
  79921. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  79922. };
  79923. };
  79924. /**
  79925. * Shader compilation success
  79926. */
  79927. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  79928. return function (_) {
  79929. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  79930. shaderMaterial.onBind = function (mesh) {
  79931. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  79932. };
  79933. };
  79934. };
  79935. /**
  79936. * Returns the appropriate uniform if already handled by babylon
  79937. */
  79938. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  79939. for (var unif in technique.uniforms) {
  79940. var uniform = technique.uniforms[unif];
  79941. var uniformParameter = technique.parameters[uniform];
  79942. if (tokenizer.currentIdentifier === unif) {
  79943. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  79944. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  79945. if (transformIndex !== -1) {
  79946. delete unTreatedUniforms[unif];
  79947. return babylonTransforms[transformIndex];
  79948. }
  79949. }
  79950. }
  79951. }
  79952. return tokenizer.currentIdentifier;
  79953. };
  79954. /**
  79955. * All shaders loaded. Create materials one by one
  79956. */
  79957. var importMaterials = function (gltfRuntime) {
  79958. // Create materials
  79959. for (var mat in gltfRuntime.materials) {
  79960. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  79961. }
  79962. };
  79963. /**
  79964. * Implementation of the base glTF spec
  79965. */
  79966. var GLTFLoaderBase = /** @class */ (function () {
  79967. function GLTFLoaderBase() {
  79968. }
  79969. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  79970. var gltfRuntime = {
  79971. extensions: {},
  79972. accessors: {},
  79973. buffers: {},
  79974. bufferViews: {},
  79975. meshes: {},
  79976. lights: {},
  79977. cameras: {},
  79978. nodes: {},
  79979. images: {},
  79980. textures: {},
  79981. shaders: {},
  79982. programs: {},
  79983. samplers: {},
  79984. techniques: {},
  79985. materials: {},
  79986. animations: {},
  79987. skins: {},
  79988. extensionsUsed: [],
  79989. scenes: {},
  79990. buffersCount: 0,
  79991. shaderscount: 0,
  79992. scene: scene,
  79993. rootUrl: rootUrl,
  79994. loadedBufferCount: 0,
  79995. loadedBufferViews: {},
  79996. loadedShaderCount: 0,
  79997. importOnlyMeshes: false,
  79998. dummyNodes: []
  79999. };
  80000. // Parse
  80001. if (parsedData.extensions) {
  80002. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  80003. }
  80004. if (parsedData.extensionsUsed) {
  80005. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  80006. }
  80007. if (parsedData.buffers) {
  80008. parseBuffers(parsedData.buffers, gltfRuntime);
  80009. }
  80010. if (parsedData.bufferViews) {
  80011. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  80012. }
  80013. if (parsedData.accessors) {
  80014. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  80015. }
  80016. if (parsedData.meshes) {
  80017. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  80018. }
  80019. if (parsedData.lights) {
  80020. parseObject(parsedData.lights, "lights", gltfRuntime);
  80021. }
  80022. if (parsedData.cameras) {
  80023. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  80024. }
  80025. if (parsedData.nodes) {
  80026. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  80027. }
  80028. if (parsedData.images) {
  80029. parseObject(parsedData.images, "images", gltfRuntime);
  80030. }
  80031. if (parsedData.textures) {
  80032. parseObject(parsedData.textures, "textures", gltfRuntime);
  80033. }
  80034. if (parsedData.shaders) {
  80035. parseShaders(parsedData.shaders, gltfRuntime);
  80036. }
  80037. if (parsedData.programs) {
  80038. parseObject(parsedData.programs, "programs", gltfRuntime);
  80039. }
  80040. if (parsedData.samplers) {
  80041. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  80042. }
  80043. if (parsedData.techniques) {
  80044. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  80045. }
  80046. if (parsedData.materials) {
  80047. parseObject(parsedData.materials, "materials", gltfRuntime);
  80048. }
  80049. if (parsedData.animations) {
  80050. parseObject(parsedData.animations, "animations", gltfRuntime);
  80051. }
  80052. if (parsedData.skins) {
  80053. parseObject(parsedData.skins, "skins", gltfRuntime);
  80054. }
  80055. if (parsedData.scenes) {
  80056. gltfRuntime.scenes = parsedData.scenes;
  80057. }
  80058. if (parsedData.scene && parsedData.scenes) {
  80059. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  80060. }
  80061. return gltfRuntime;
  80062. };
  80063. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80064. var buffer = gltfRuntime.buffers[id];
  80065. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  80066. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  80067. }
  80068. else {
  80069. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  80070. if (request) {
  80071. onError(request.status + " " + request.statusText);
  80072. }
  80073. });
  80074. }
  80075. };
  80076. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80077. var texture = gltfRuntime.textures[id];
  80078. if (!texture || !texture.source) {
  80079. onError("");
  80080. return;
  80081. }
  80082. if (texture.babylonTexture) {
  80083. onSuccess(null);
  80084. return;
  80085. }
  80086. var source = gltfRuntime.images[texture.source];
  80087. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  80088. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  80089. }
  80090. else {
  80091. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  80092. if (request) {
  80093. onError(request.status + " " + request.statusText);
  80094. }
  80095. });
  80096. }
  80097. };
  80098. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80099. var texture = gltfRuntime.textures[id];
  80100. if (texture.babylonTexture) {
  80101. onSuccess(texture.babylonTexture);
  80102. return;
  80103. }
  80104. var sampler = gltfRuntime.samplers[texture.sampler];
  80105. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  80106. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  80107. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  80108. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  80109. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  80110. var blob = new Blob([buffer]);
  80111. var blobURL = URL.createObjectURL(blob);
  80112. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  80113. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  80114. if (sampler.wrapS !== undefined) {
  80115. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  80116. }
  80117. if (sampler.wrapT !== undefined) {
  80118. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  80119. }
  80120. newTexture.name = id;
  80121. texture.babylonTexture = newTexture;
  80122. onSuccess(newTexture);
  80123. };
  80124. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80125. var shader = gltfRuntime.shaders[id];
  80126. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  80127. var shaderString = atob(shader.uri.split(",")[1]);
  80128. onSuccess(shaderString);
  80129. }
  80130. else {
  80131. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  80132. if (request) {
  80133. onError(request.status + " " + request.statusText);
  80134. }
  80135. });
  80136. }
  80137. };
  80138. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80139. var material = gltfRuntime.materials[id];
  80140. if (!material.technique) {
  80141. if (onError) {
  80142. onError("No technique found.");
  80143. }
  80144. return;
  80145. }
  80146. var technique = gltfRuntime.techniques[material.technique];
  80147. if (!technique) {
  80148. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  80149. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  80150. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80151. onSuccess(defaultMaterial);
  80152. return;
  80153. }
  80154. var program = gltfRuntime.programs[technique.program];
  80155. var states = technique.states;
  80156. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  80157. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  80158. var newVertexShader = "";
  80159. var newPixelShader = "";
  80160. var vertexTokenizer = new Tokenizer(vertexShader);
  80161. var pixelTokenizer = new Tokenizer(pixelShader);
  80162. var unTreatedUniforms = {};
  80163. var uniforms = [];
  80164. var attributes = [];
  80165. var samplers = [];
  80166. // Fill uniform, sampler2D and attributes
  80167. for (var unif in technique.uniforms) {
  80168. var uniform = technique.uniforms[unif];
  80169. var uniformParameter = technique.parameters[uniform];
  80170. unTreatedUniforms[unif] = uniformParameter;
  80171. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  80172. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  80173. if (transformIndex !== -1) {
  80174. uniforms.push(babylonTransforms[transformIndex]);
  80175. delete unTreatedUniforms[unif];
  80176. }
  80177. else {
  80178. uniforms.push(unif);
  80179. }
  80180. }
  80181. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  80182. samplers.push(unif);
  80183. }
  80184. else {
  80185. uniforms.push(unif);
  80186. }
  80187. }
  80188. for (var attr in technique.attributes) {
  80189. var attribute = technique.attributes[attr];
  80190. var attributeParameter = technique.parameters[attribute];
  80191. if (attributeParameter.semantic) {
  80192. attributes.push(getAttribute(attributeParameter));
  80193. }
  80194. }
  80195. // Configure vertex shader
  80196. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  80197. var tokenType = vertexTokenizer.currentToken;
  80198. if (tokenType !== ETokenType.IDENTIFIER) {
  80199. newVertexShader += vertexTokenizer.currentString;
  80200. continue;
  80201. }
  80202. var foundAttribute = false;
  80203. for (var attr in technique.attributes) {
  80204. var attribute = technique.attributes[attr];
  80205. var attributeParameter = technique.parameters[attribute];
  80206. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  80207. newVertexShader += getAttribute(attributeParameter);
  80208. foundAttribute = true;
  80209. break;
  80210. }
  80211. }
  80212. if (foundAttribute) {
  80213. continue;
  80214. }
  80215. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  80216. }
  80217. // Configure pixel shader
  80218. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  80219. var tokenType = pixelTokenizer.currentToken;
  80220. if (tokenType !== ETokenType.IDENTIFIER) {
  80221. newPixelShader += pixelTokenizer.currentString;
  80222. continue;
  80223. }
  80224. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  80225. }
  80226. // Create shader material
  80227. var shaderPath = {
  80228. vertex: program.vertexShader + id,
  80229. fragment: program.fragmentShader + id
  80230. };
  80231. var options = {
  80232. attributes: attributes,
  80233. uniforms: uniforms,
  80234. samplers: samplers,
  80235. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  80236. };
  80237. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  80238. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  80239. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  80240. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  80241. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  80242. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80243. if (states && states.functions) {
  80244. var functions = states.functions;
  80245. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  80246. shaderMaterial.backFaceCulling = false;
  80247. }
  80248. var blendFunc = functions.blendFuncSeparate;
  80249. if (blendFunc) {
  80250. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80251. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  80252. }
  80253. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80254. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80255. }
  80256. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80257. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  80258. }
  80259. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80260. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  80261. }
  80262. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80263. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  80264. }
  80265. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80266. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  80267. }
  80268. }
  80269. }
  80270. };
  80271. return GLTFLoaderBase;
  80272. }());
  80273. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  80274. /**
  80275. * glTF V1 Loader
  80276. */
  80277. var GLTFLoader = /** @class */ (function () {
  80278. function GLTFLoader() {
  80279. }
  80280. GLTFLoader.RegisterExtension = function (extension) {
  80281. if (GLTFLoader.Extensions[extension.name]) {
  80282. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  80283. return;
  80284. }
  80285. GLTFLoader.Extensions[extension.name] = extension;
  80286. };
  80287. GLTFLoader.prototype.dispose = function () {
  80288. // do nothing
  80289. };
  80290. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80291. var _this = this;
  80292. scene.useRightHandedSystem = true;
  80293. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  80294. gltfRuntime.importOnlyMeshes = true;
  80295. if (meshesNames === "") {
  80296. gltfRuntime.importMeshesNames = [];
  80297. }
  80298. else if (typeof meshesNames === "string") {
  80299. gltfRuntime.importMeshesNames = [meshesNames];
  80300. }
  80301. else if (meshesNames && !(meshesNames instanceof Array)) {
  80302. gltfRuntime.importMeshesNames = [meshesNames];
  80303. }
  80304. else {
  80305. gltfRuntime.importMeshesNames = [];
  80306. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  80307. }
  80308. // Create nodes
  80309. _this._createNodes(gltfRuntime);
  80310. var meshes = new Array();
  80311. var skeletons = new Array();
  80312. // Fill arrays of meshes and skeletons
  80313. for (var nde in gltfRuntime.nodes) {
  80314. var node = gltfRuntime.nodes[nde];
  80315. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  80316. meshes.push(node.babylonNode);
  80317. }
  80318. }
  80319. for (var skl in gltfRuntime.skins) {
  80320. var skin = gltfRuntime.skins[skl];
  80321. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  80322. skeletons.push(skin.babylonSkeleton);
  80323. }
  80324. }
  80325. // Load buffers, shaders, materials, etc.
  80326. _this._loadBuffersAsync(gltfRuntime, function () {
  80327. _this._loadShadersAsync(gltfRuntime, function () {
  80328. importMaterials(gltfRuntime);
  80329. postLoad(gltfRuntime);
  80330. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  80331. onSuccess(meshes, [], skeletons);
  80332. }
  80333. });
  80334. }, onProgress);
  80335. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  80336. onSuccess(meshes, [], skeletons);
  80337. }
  80338. }, onError);
  80339. return true;
  80340. };
  80341. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80342. var _this = this;
  80343. scene.useRightHandedSystem = true;
  80344. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  80345. // Load runtime extensios
  80346. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  80347. // Create nodes
  80348. _this._createNodes(gltfRuntime);
  80349. // Load buffers, shaders, materials, etc.
  80350. _this._loadBuffersAsync(gltfRuntime, function () {
  80351. _this._loadShadersAsync(gltfRuntime, function () {
  80352. importMaterials(gltfRuntime);
  80353. postLoad(gltfRuntime);
  80354. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  80355. onSuccess();
  80356. }
  80357. });
  80358. });
  80359. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  80360. onSuccess();
  80361. }
  80362. }, onError);
  80363. }, onError);
  80364. };
  80365. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  80366. var hasShaders = false;
  80367. var processShader = function (sha, shader) {
  80368. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  80369. gltfRuntime.loadedShaderCount++;
  80370. if (shaderString) {
  80371. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  80372. }
  80373. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  80374. onload();
  80375. }
  80376. }, function () {
  80377. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  80378. });
  80379. };
  80380. for (var sha in gltfRuntime.shaders) {
  80381. hasShaders = true;
  80382. var shader = gltfRuntime.shaders[sha];
  80383. if (shader) {
  80384. processShader.bind(this, sha, shader)();
  80385. }
  80386. else {
  80387. BABYLON.Tools.Error("No shader named: " + sha);
  80388. }
  80389. }
  80390. if (!hasShaders) {
  80391. onload();
  80392. }
  80393. };
  80394. ;
  80395. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  80396. var hasBuffers = false;
  80397. var processBuffer = function (buf, buffer) {
  80398. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  80399. gltfRuntime.loadedBufferCount++;
  80400. if (bufferView) {
  80401. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  80402. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  80403. }
  80404. gltfRuntime.loadedBufferViews[buf] = bufferView;
  80405. }
  80406. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  80407. onLoad();
  80408. }
  80409. }, function () {
  80410. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  80411. });
  80412. };
  80413. for (var buf in gltfRuntime.buffers) {
  80414. hasBuffers = true;
  80415. var buffer = gltfRuntime.buffers[buf];
  80416. if (buffer) {
  80417. processBuffer.bind(this, buf, buffer)();
  80418. }
  80419. else {
  80420. BABYLON.Tools.Error("No buffer named: " + buf);
  80421. }
  80422. }
  80423. if (!hasBuffers) {
  80424. onLoad();
  80425. }
  80426. };
  80427. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  80428. var currentScene = gltfRuntime.currentScene;
  80429. if (currentScene) {
  80430. // Only one scene even if multiple scenes are defined
  80431. for (var i = 0; i < currentScene.nodes.length; i++) {
  80432. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80433. }
  80434. }
  80435. else {
  80436. // Load all scenes
  80437. for (var thing in gltfRuntime.scenes) {
  80438. currentScene = gltfRuntime.scenes[thing];
  80439. for (var i = 0; i < currentScene.nodes.length; i++) {
  80440. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80441. }
  80442. }
  80443. }
  80444. };
  80445. GLTFLoader.Extensions = {};
  80446. return GLTFLoader;
  80447. }());
  80448. GLTF1.GLTFLoader = GLTFLoader;
  80449. ;
  80450. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  80451. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80452. })(BABYLON || (BABYLON = {}));
  80453. //# sourceMappingURL=babylon.glTFLoader.js.map
  80454. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80455. var BABYLON;
  80456. (function (BABYLON) {
  80457. var GLTF1;
  80458. (function (GLTF1) {
  80459. /**
  80460. * Utils functions for GLTF
  80461. */
  80462. var GLTFUtils = /** @class */ (function () {
  80463. function GLTFUtils() {
  80464. }
  80465. /**
  80466. * Sets the given "parameter" matrix
  80467. * @param scene: the {BABYLON.Scene} object
  80468. * @param source: the source node where to pick the matrix
  80469. * @param parameter: the GLTF technique parameter
  80470. * @param uniformName: the name of the shader's uniform
  80471. * @param shaderMaterial: the shader material
  80472. */
  80473. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  80474. var mat = null;
  80475. if (parameter.semantic === "MODEL") {
  80476. mat = source.getWorldMatrix();
  80477. }
  80478. else if (parameter.semantic === "PROJECTION") {
  80479. mat = scene.getProjectionMatrix();
  80480. }
  80481. else if (parameter.semantic === "VIEW") {
  80482. mat = scene.getViewMatrix();
  80483. }
  80484. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  80485. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  80486. }
  80487. else if (parameter.semantic === "MODELVIEW") {
  80488. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  80489. }
  80490. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  80491. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  80492. }
  80493. else if (parameter.semantic === "MODELINVERSE") {
  80494. mat = source.getWorldMatrix().invert();
  80495. }
  80496. else if (parameter.semantic === "VIEWINVERSE") {
  80497. mat = scene.getViewMatrix().invert();
  80498. }
  80499. else if (parameter.semantic === "PROJECTIONINVERSE") {
  80500. mat = scene.getProjectionMatrix().invert();
  80501. }
  80502. else if (parameter.semantic === "MODELVIEWINVERSE") {
  80503. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  80504. }
  80505. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  80506. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  80507. }
  80508. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  80509. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  80510. }
  80511. else {
  80512. debugger;
  80513. }
  80514. if (mat) {
  80515. switch (parameter.type) {
  80516. case GLTF1.EParameterType.FLOAT_MAT2:
  80517. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  80518. break;
  80519. case GLTF1.EParameterType.FLOAT_MAT3:
  80520. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  80521. break;
  80522. case GLTF1.EParameterType.FLOAT_MAT4:
  80523. shaderMaterial.setMatrix(uniformName, mat);
  80524. break;
  80525. default: break;
  80526. }
  80527. }
  80528. };
  80529. /**
  80530. * Sets the given "parameter" matrix
  80531. * @param shaderMaterial: the shader material
  80532. * @param uniform: the name of the shader's uniform
  80533. * @param value: the value of the uniform
  80534. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  80535. */
  80536. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  80537. switch (type) {
  80538. case GLTF1.EParameterType.FLOAT:
  80539. shaderMaterial.setFloat(uniform, value);
  80540. return true;
  80541. case GLTF1.EParameterType.FLOAT_VEC2:
  80542. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  80543. return true;
  80544. case GLTF1.EParameterType.FLOAT_VEC3:
  80545. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  80546. return true;
  80547. case GLTF1.EParameterType.FLOAT_VEC4:
  80548. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  80549. return true;
  80550. default: return false;
  80551. }
  80552. };
  80553. /**
  80554. * If the uri is a base64 string
  80555. * @param uri: the uri to test
  80556. */
  80557. GLTFUtils.IsBase64 = function (uri) {
  80558. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  80559. };
  80560. /**
  80561. * Decode the base64 uri
  80562. * @param uri: the uri to decode
  80563. */
  80564. GLTFUtils.DecodeBase64 = function (uri) {
  80565. var decodedString = atob(uri.split(",")[1]);
  80566. var bufferLength = decodedString.length;
  80567. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  80568. for (var i = 0; i < bufferLength; i++) {
  80569. bufferView[i] = decodedString.charCodeAt(i);
  80570. }
  80571. return bufferView.buffer;
  80572. };
  80573. /**
  80574. * Returns the wrap mode of the texture
  80575. * @param mode: the mode value
  80576. */
  80577. GLTFUtils.GetWrapMode = function (mode) {
  80578. switch (mode) {
  80579. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  80580. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  80581. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80582. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80583. }
  80584. };
  80585. /**
  80586. * Returns the byte stride giving an accessor
  80587. * @param accessor: the GLTF accessor objet
  80588. */
  80589. GLTFUtils.GetByteStrideFromType = function (accessor) {
  80590. // Needs this function since "byteStride" isn't requiered in glTF format
  80591. var type = accessor.type;
  80592. switch (type) {
  80593. case "VEC2": return 2;
  80594. case "VEC3": return 3;
  80595. case "VEC4": return 4;
  80596. case "MAT2": return 4;
  80597. case "MAT3": return 9;
  80598. case "MAT4": return 16;
  80599. default: return 1;
  80600. }
  80601. };
  80602. /**
  80603. * Returns the texture filter mode giving a mode value
  80604. * @param mode: the filter mode value
  80605. */
  80606. GLTFUtils.GetTextureFilterMode = function (mode) {
  80607. switch (mode) {
  80608. case GLTF1.ETextureFilterType.LINEAR:
  80609. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  80610. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  80611. case GLTF1.ETextureFilterType.NEAREST:
  80612. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  80613. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  80614. }
  80615. };
  80616. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  80617. var byteOffset = bufferView.byteOffset + byteOffset;
  80618. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  80619. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  80620. throw new Error("Buffer access is out of range");
  80621. }
  80622. var buffer = loadedBufferView.buffer;
  80623. byteOffset += loadedBufferView.byteOffset;
  80624. switch (componentType) {
  80625. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  80626. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  80627. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  80628. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  80629. default: return new Float32Array(buffer, byteOffset, byteLength);
  80630. }
  80631. };
  80632. /**
  80633. * Returns a buffer from its accessor
  80634. * @param gltfRuntime: the GLTF runtime
  80635. * @param accessor: the GLTF accessor
  80636. */
  80637. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  80638. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  80639. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  80640. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  80641. };
  80642. /**
  80643. * Decodes a buffer view into a string
  80644. * @param view: the buffer view
  80645. */
  80646. GLTFUtils.DecodeBufferToText = function (view) {
  80647. var result = "";
  80648. var length = view.byteLength;
  80649. for (var i = 0; i < length; ++i) {
  80650. result += String.fromCharCode(view[i]);
  80651. }
  80652. return result;
  80653. };
  80654. /**
  80655. * Returns the default material of gltf. Related to
  80656. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  80657. * @param scene: the Babylon.js scene
  80658. */
  80659. GLTFUtils.GetDefaultMaterial = function (scene) {
  80660. if (!GLTFUtils._DefaultMaterial) {
  80661. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  80662. "precision highp float;",
  80663. "",
  80664. "uniform mat4 worldView;",
  80665. "uniform mat4 projection;",
  80666. "",
  80667. "attribute vec3 position;",
  80668. "",
  80669. "void main(void)",
  80670. "{",
  80671. " gl_Position = projection * worldView * vec4(position, 1.0);",
  80672. "}"
  80673. ].join("\n");
  80674. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  80675. "precision highp float;",
  80676. "",
  80677. "uniform vec4 u_emission;",
  80678. "",
  80679. "void main(void)",
  80680. "{",
  80681. " gl_FragColor = u_emission;",
  80682. "}"
  80683. ].join("\n");
  80684. var shaderPath = {
  80685. vertex: "GLTFDefaultMaterial",
  80686. fragment: "GLTFDefaultMaterial"
  80687. };
  80688. var options = {
  80689. attributes: ["position"],
  80690. uniforms: ["worldView", "projection", "u_emission"],
  80691. samplers: new Array(),
  80692. needAlphaBlending: false
  80693. };
  80694. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  80695. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  80696. }
  80697. return GLTFUtils._DefaultMaterial;
  80698. };
  80699. // The GLTF default material
  80700. GLTFUtils._DefaultMaterial = null;
  80701. return GLTFUtils;
  80702. }());
  80703. GLTF1.GLTFUtils = GLTFUtils;
  80704. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80705. })(BABYLON || (BABYLON = {}));
  80706. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  80707. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80708. var BABYLON;
  80709. (function (BABYLON) {
  80710. var GLTF1;
  80711. (function (GLTF1) {
  80712. var GLTFLoaderExtension = /** @class */ (function () {
  80713. function GLTFLoaderExtension(name) {
  80714. this._name = name;
  80715. }
  80716. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  80717. get: function () {
  80718. return this._name;
  80719. },
  80720. enumerable: true,
  80721. configurable: true
  80722. });
  80723. /**
  80724. * Defines an override for loading the runtime
  80725. * Return true to stop further extensions from loading the runtime
  80726. */
  80727. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80728. return false;
  80729. };
  80730. /**
  80731. * Defines an onverride for creating gltf runtime
  80732. * Return true to stop further extensions from creating the runtime
  80733. */
  80734. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80735. return false;
  80736. };
  80737. /**
  80738. * Defines an override for loading buffers
  80739. * Return true to stop further extensions from loading this buffer
  80740. */
  80741. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80742. return false;
  80743. };
  80744. /**
  80745. * Defines an override for loading texture buffers
  80746. * Return true to stop further extensions from loading this texture data
  80747. */
  80748. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80749. return false;
  80750. };
  80751. /**
  80752. * Defines an override for creating textures
  80753. * Return true to stop further extensions from loading this texture
  80754. */
  80755. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80756. return false;
  80757. };
  80758. /**
  80759. * Defines an override for loading shader strings
  80760. * Return true to stop further extensions from loading this shader data
  80761. */
  80762. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80763. return false;
  80764. };
  80765. /**
  80766. * Defines an override for loading materials
  80767. * Return true to stop further extensions from loading this material
  80768. */
  80769. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80770. return false;
  80771. };
  80772. // ---------
  80773. // Utilities
  80774. // ---------
  80775. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80776. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80777. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  80778. }, function () {
  80779. setTimeout(function () {
  80780. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  80781. });
  80782. });
  80783. };
  80784. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80785. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80786. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  80787. }, function () {
  80788. setTimeout(function () {
  80789. onSuccess();
  80790. });
  80791. });
  80792. };
  80793. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80794. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80795. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  80796. }, function () {
  80797. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  80798. });
  80799. };
  80800. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  80801. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  80802. };
  80803. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80804. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80805. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  80806. }, function () {
  80807. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  80808. });
  80809. };
  80810. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80811. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80812. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  80813. }, function () {
  80814. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  80815. });
  80816. };
  80817. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80818. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80819. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  80820. }, function () {
  80821. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  80822. });
  80823. };
  80824. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80825. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  80826. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  80827. }, function () {
  80828. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  80829. });
  80830. };
  80831. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  80832. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  80833. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  80834. if (func(loaderExtension)) {
  80835. return;
  80836. }
  80837. }
  80838. defaultFunc();
  80839. };
  80840. return GLTFLoaderExtension;
  80841. }());
  80842. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  80843. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80844. })(BABYLON || (BABYLON = {}));
  80845. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  80846. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80847. var BABYLON;
  80848. (function (BABYLON) {
  80849. var GLTF1;
  80850. (function (GLTF1) {
  80851. var BinaryExtensionBufferName = "binary_glTF";
  80852. ;
  80853. ;
  80854. var GLTFBinaryExtension = /** @class */ (function (_super) {
  80855. __extends(GLTFBinaryExtension, _super);
  80856. function GLTFBinaryExtension() {
  80857. return _super.call(this, "KHR_binary_glTF") || this;
  80858. }
  80859. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  80860. var extensionsUsed = data.json.extensionsUsed;
  80861. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  80862. return false;
  80863. }
  80864. this._bin = data.bin;
  80865. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  80866. return true;
  80867. };
  80868. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80869. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  80870. return false;
  80871. }
  80872. if (id !== BinaryExtensionBufferName) {
  80873. return false;
  80874. }
  80875. onSuccess(this._bin);
  80876. return true;
  80877. };
  80878. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80879. var texture = gltfRuntime.textures[id];
  80880. var source = gltfRuntime.images[texture.source];
  80881. if (!source.extensions || !(this.name in source.extensions)) {
  80882. return false;
  80883. }
  80884. var sourceExt = source.extensions[this.name];
  80885. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  80886. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  80887. onSuccess(buffer);
  80888. return true;
  80889. };
  80890. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80891. var shader = gltfRuntime.shaders[id];
  80892. if (!shader.extensions || !(this.name in shader.extensions)) {
  80893. return false;
  80894. }
  80895. var binaryExtensionShader = shader.extensions[this.name];
  80896. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  80897. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  80898. setTimeout(function () {
  80899. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  80900. onSuccess(shaderString);
  80901. });
  80902. return true;
  80903. };
  80904. return GLTFBinaryExtension;
  80905. }(GLTF1.GLTFLoaderExtension));
  80906. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  80907. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  80908. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80909. })(BABYLON || (BABYLON = {}));
  80910. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  80911. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80912. var BABYLON;
  80913. (function (BABYLON) {
  80914. var GLTF1;
  80915. (function (GLTF1) {
  80916. ;
  80917. ;
  80918. ;
  80919. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  80920. __extends(GLTFMaterialsCommonExtension, _super);
  80921. function GLTFMaterialsCommonExtension() {
  80922. return _super.call(this, "KHR_materials_common") || this;
  80923. }
  80924. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80925. if (!gltfRuntime.extensions)
  80926. return false;
  80927. var extension = gltfRuntime.extensions[this.name];
  80928. if (!extension)
  80929. return false;
  80930. // Create lights
  80931. var lights = extension.lights;
  80932. if (lights) {
  80933. for (var thing in lights) {
  80934. var light = lights[thing];
  80935. switch (light.type) {
  80936. case "ambient":
  80937. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  80938. var ambient = light.ambient;
  80939. if (ambient) {
  80940. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  80941. }
  80942. break;
  80943. case "point":
  80944. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  80945. var point = light.point;
  80946. if (point) {
  80947. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  80948. }
  80949. break;
  80950. case "directional":
  80951. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  80952. var directional = light.directional;
  80953. if (directional) {
  80954. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  80955. }
  80956. break;
  80957. case "spot":
  80958. var spot = light.spot;
  80959. if (spot) {
  80960. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  80961. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  80962. }
  80963. break;
  80964. default:
  80965. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  80966. break;
  80967. }
  80968. }
  80969. }
  80970. return false;
  80971. };
  80972. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80973. var material = gltfRuntime.materials[id];
  80974. if (!material || !material.extensions)
  80975. return false;
  80976. var extension = material.extensions[this.name];
  80977. if (!extension)
  80978. return false;
  80979. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  80980. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80981. if (extension.technique === "CONSTANT") {
  80982. standardMaterial.disableLighting = true;
  80983. }
  80984. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  80985. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  80986. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  80987. // Ambient
  80988. if (typeof extension.values.ambient === "string") {
  80989. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  80990. }
  80991. else {
  80992. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  80993. }
  80994. // Diffuse
  80995. if (typeof extension.values.diffuse === "string") {
  80996. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  80997. }
  80998. else {
  80999. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  81000. }
  81001. // Emission
  81002. if (typeof extension.values.emission === "string") {
  81003. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  81004. }
  81005. else {
  81006. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  81007. }
  81008. // Specular
  81009. if (typeof extension.values.specular === "string") {
  81010. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  81011. }
  81012. else {
  81013. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  81014. }
  81015. return true;
  81016. };
  81017. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  81018. // Create buffer from texture url
  81019. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  81020. // Create texture from buffer
  81021. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  81022. }, onError);
  81023. };
  81024. return GLTFMaterialsCommonExtension;
  81025. }(GLTF1.GLTFLoaderExtension));
  81026. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  81027. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  81028. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81029. })(BABYLON || (BABYLON = {}));
  81030. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  81031. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81032. var BABYLON;
  81033. (function (BABYLON) {
  81034. var GLTF2;
  81035. (function (GLTF2) {
  81036. /**
  81037. * Enums
  81038. */
  81039. var EComponentType;
  81040. (function (EComponentType) {
  81041. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  81042. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  81043. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  81044. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  81045. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  81046. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  81047. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  81048. var EMeshPrimitiveMode;
  81049. (function (EMeshPrimitiveMode) {
  81050. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  81051. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  81052. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  81053. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  81054. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  81055. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  81056. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  81057. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  81058. var ETextureMagFilter;
  81059. (function (ETextureMagFilter) {
  81060. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  81061. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  81062. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  81063. var ETextureMinFilter;
  81064. (function (ETextureMinFilter) {
  81065. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  81066. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  81067. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  81068. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  81069. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  81070. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  81071. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  81072. var ETextureWrapMode;
  81073. (function (ETextureWrapMode) {
  81074. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  81075. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  81076. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  81077. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  81078. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81079. })(BABYLON || (BABYLON = {}));
  81080. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  81081. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81082. var BABYLON;
  81083. (function (BABYLON) {
  81084. var GLTF2;
  81085. (function (GLTF2) {
  81086. var GLTFLoaderTracker = /** @class */ (function () {
  81087. function GLTFLoaderTracker(onComplete) {
  81088. this._pendingCount = 0;
  81089. this._callback = onComplete;
  81090. }
  81091. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  81092. this._pendingCount++;
  81093. };
  81094. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  81095. if (--this._pendingCount === 0) {
  81096. this._callback();
  81097. }
  81098. };
  81099. return GLTFLoaderTracker;
  81100. }());
  81101. var GLTFLoader = /** @class */ (function () {
  81102. function GLTFLoader(parent) {
  81103. this._disposed = false;
  81104. this._renderReady = false;
  81105. this._requests = new Array();
  81106. this._renderReadyObservable = new BABYLON.Observable();
  81107. // Count of pending work that needs to complete before the asset is rendered.
  81108. this._renderPendingCount = 0;
  81109. // Count of pending work that needs to complete before the loader is disposed.
  81110. this._loaderPendingCount = 0;
  81111. this._loaderTrackers = new Array();
  81112. this._parent = parent;
  81113. if (!GLTFLoader._progressEventFactory) {
  81114. if (typeof window["ProgressEvent"] === "function") {
  81115. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  81116. }
  81117. else {
  81118. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  81119. }
  81120. }
  81121. }
  81122. GLTFLoader.RegisterExtension = function (extension) {
  81123. if (GLTFLoader.Extensions[extension.name]) {
  81124. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  81125. return;
  81126. }
  81127. GLTFLoader.Extensions[extension.name] = extension;
  81128. // Keep the order of registration so that extensions registered first are called first.
  81129. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  81130. };
  81131. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  81132. return new ProgressEvent(name, data);
  81133. };
  81134. GLTFLoader._createProgressEventByDocument = function (name, data) {
  81135. var event = document.createEvent("ProgressEvent");
  81136. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  81137. return event;
  81138. };
  81139. GLTFLoader.prototype.dispose = function () {
  81140. if (this._disposed) {
  81141. return;
  81142. }
  81143. this._disposed = true;
  81144. // Abort requests that are not complete
  81145. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  81146. var request = _a[_i];
  81147. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  81148. request.abort();
  81149. }
  81150. }
  81151. // Revoke object urls created during load
  81152. if (this._gltf.textures) {
  81153. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  81154. var texture = _c[_b];
  81155. if (texture.url) {
  81156. URL.revokeObjectURL(texture.url);
  81157. }
  81158. }
  81159. }
  81160. };
  81161. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81162. var _this = this;
  81163. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  81164. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  81165. }, onProgress, onError);
  81166. };
  81167. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81168. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  81169. };
  81170. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81171. var _this = this;
  81172. this._tryCatchOnError(function () {
  81173. _this._loadData(data);
  81174. _this._babylonScene = scene;
  81175. _this._rootUrl = rootUrl;
  81176. _this._successCallback = onSuccess;
  81177. _this._progressCallback = onProgress;
  81178. _this._errorCallback = onError;
  81179. _this._addPendingData(_this);
  81180. _this._loadDefaultScene(nodeNames);
  81181. _this._loadAnimations();
  81182. _this._removePendingData(_this);
  81183. });
  81184. };
  81185. GLTFLoader.prototype._onProgress = function () {
  81186. if (!this._progressCallback) {
  81187. return;
  81188. }
  81189. var loaded = 0;
  81190. var total = 0;
  81191. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  81192. var request = _a[_i];
  81193. if (!request._loaded || !request._total) {
  81194. return;
  81195. }
  81196. loaded += request._loaded;
  81197. total += request._total;
  81198. }
  81199. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  81200. lengthComputable: true,
  81201. loaded: loaded,
  81202. total: total
  81203. }));
  81204. };
  81205. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  81206. if (this._renderReady) {
  81207. func();
  81208. }
  81209. else {
  81210. this._renderReadyObservable.add(func);
  81211. }
  81212. };
  81213. GLTFLoader.prototype._onRenderReady = function () {
  81214. this._rootNode.babylonMesh.setEnabled(true);
  81215. this._startAnimations();
  81216. this._successCallback();
  81217. this._renderReadyObservable.notifyObservers(this);
  81218. };
  81219. GLTFLoader.prototype._onComplete = function () {
  81220. if (this._parent.onComplete) {
  81221. this._parent.onComplete();
  81222. }
  81223. this.dispose();
  81224. };
  81225. GLTFLoader.prototype._loadData = function (data) {
  81226. this._gltf = data.json;
  81227. // Assign the index of each object for convinience.
  81228. GLTFLoader._AssignIndices(this._gltf.accessors);
  81229. GLTFLoader._AssignIndices(this._gltf.animations);
  81230. GLTFLoader._AssignIndices(this._gltf.buffers);
  81231. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  81232. GLTFLoader._AssignIndices(this._gltf.images);
  81233. GLTFLoader._AssignIndices(this._gltf.materials);
  81234. GLTFLoader._AssignIndices(this._gltf.meshes);
  81235. GLTFLoader._AssignIndices(this._gltf.nodes);
  81236. GLTFLoader._AssignIndices(this._gltf.scenes);
  81237. GLTFLoader._AssignIndices(this._gltf.skins);
  81238. GLTFLoader._AssignIndices(this._gltf.textures);
  81239. if (data.bin) {
  81240. var buffers = this._gltf.buffers;
  81241. if (buffers && buffers[0] && !buffers[0].uri) {
  81242. var binaryBuffer = buffers[0];
  81243. if (binaryBuffer.byteLength != data.bin.byteLength) {
  81244. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  81245. }
  81246. binaryBuffer.loadedData = data.bin;
  81247. }
  81248. else {
  81249. BABYLON.Tools.Warn("Unexpected BIN chunk");
  81250. }
  81251. }
  81252. };
  81253. GLTFLoader.prototype._getMeshes = function () {
  81254. var meshes = new Array();
  81255. // Root mesh is always first.
  81256. meshes.push(this._rootNode.babylonMesh);
  81257. var nodes = this._gltf.nodes;
  81258. if (nodes) {
  81259. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  81260. var node = nodes_1[_i];
  81261. if (node.babylonMesh) {
  81262. meshes.push(node.babylonMesh);
  81263. }
  81264. }
  81265. }
  81266. return meshes;
  81267. };
  81268. GLTFLoader.prototype._getSkeletons = function () {
  81269. var skeletons = new Array();
  81270. var skins = this._gltf.skins;
  81271. if (skins) {
  81272. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  81273. var skin = skins_1[_i];
  81274. if (skin.babylonSkeleton) {
  81275. skeletons.push(skin.babylonSkeleton);
  81276. }
  81277. }
  81278. }
  81279. return skeletons;
  81280. };
  81281. GLTFLoader.prototype._getAnimationTargets = function () {
  81282. var targets = new Array();
  81283. var animations = this._gltf.animations;
  81284. if (animations) {
  81285. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  81286. var animation = animations_1[_i];
  81287. targets.push.apply(targets, animation.targets);
  81288. }
  81289. }
  81290. return targets;
  81291. };
  81292. GLTFLoader.prototype._startAnimations = function () {
  81293. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  81294. var target = _a[_i];
  81295. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  81296. }
  81297. };
  81298. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  81299. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  81300. if (!scene) {
  81301. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  81302. }
  81303. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  81304. };
  81305. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  81306. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  81307. switch (this._parent.coordinateSystemMode) {
  81308. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  81309. if (!this._babylonScene.useRightHandedSystem) {
  81310. this._rootNode.rotation = [0, 1, 0, 0];
  81311. this._rootNode.scale = [1, 1, -1];
  81312. this._loadTransform(this._rootNode);
  81313. }
  81314. break;
  81315. }
  81316. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  81317. // do nothing
  81318. break;
  81319. }
  81320. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  81321. this._babylonScene.useRightHandedSystem = true;
  81322. break;
  81323. }
  81324. default: {
  81325. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  81326. return;
  81327. }
  81328. }
  81329. if (this._parent.onMeshLoaded) {
  81330. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  81331. }
  81332. var nodeIndices = scene.nodes;
  81333. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  81334. node.parent = parentNode;
  81335. return true;
  81336. }, this._rootNode);
  81337. if (nodeNames) {
  81338. if (!(nodeNames instanceof Array)) {
  81339. nodeNames = [nodeNames];
  81340. }
  81341. var filteredNodeIndices_1 = new Array();
  81342. this._traverseNodes(context, nodeIndices, function (node) {
  81343. if (nodeNames.indexOf(node.name) !== -1) {
  81344. filteredNodeIndices_1.push(node.index);
  81345. return false;
  81346. }
  81347. return true;
  81348. }, this._rootNode);
  81349. nodeIndices = filteredNodeIndices_1;
  81350. }
  81351. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  81352. var index = nodeIndices_1[_i];
  81353. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81354. if (!node) {
  81355. throw new Error(context + ": Failed to find node " + index);
  81356. }
  81357. this._loadNode("#/nodes/" + index, node);
  81358. }
  81359. // Disable the root mesh until the asset is ready to render.
  81360. this._rootNode.babylonMesh.setEnabled(false);
  81361. };
  81362. GLTFLoader.prototype._loadNode = function (context, node) {
  81363. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  81364. return;
  81365. }
  81366. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  81367. node.babylonMesh.hasVertexAlpha = true;
  81368. this._loadTransform(node);
  81369. if (node.mesh != null) {
  81370. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  81371. if (!mesh) {
  81372. throw new Error(context + ": Failed to find mesh " + node.mesh);
  81373. }
  81374. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  81375. }
  81376. node.babylonMesh.parent = node.parent.babylonMesh;
  81377. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  81378. node.babylonAnimationTargets.push(node.babylonMesh);
  81379. if (node.skin != null) {
  81380. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  81381. if (!skin_1) {
  81382. throw new Error(context + ": Failed to find skin " + node.skin);
  81383. }
  81384. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  81385. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  81386. node.babylonMesh._refreshBoundingInfo(true);
  81387. });
  81388. node.babylonMesh.parent = this._rootNode.babylonMesh;
  81389. node.babylonMesh.position = BABYLON.Vector3.Zero();
  81390. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  81391. node.babylonMesh.scaling = BABYLON.Vector3.One();
  81392. }
  81393. if (node.camera != null) {
  81394. // TODO: handle cameras
  81395. }
  81396. if (node.children) {
  81397. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  81398. var index = _a[_i];
  81399. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81400. if (!childNode) {
  81401. throw new Error(context + ": Failed to find child node " + index);
  81402. }
  81403. this._loadNode("#/nodes/" + index, childNode);
  81404. }
  81405. }
  81406. if (this._parent.onMeshLoaded) {
  81407. this._parent.onMeshLoaded(node.babylonMesh);
  81408. }
  81409. };
  81410. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  81411. var _this = this;
  81412. var primitives = mesh.primitives;
  81413. if (!primitives || primitives.length === 0) {
  81414. throw new Error(context + ": Primitives are missing");
  81415. }
  81416. this._createMorphTargets(context, node, mesh);
  81417. this._loadAllVertexDataAsync(context, mesh, function () {
  81418. _this._loadMorphTargets(context, node, mesh);
  81419. var vertexData = new BABYLON.VertexData();
  81420. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  81421. var primitive = primitives_1[_i];
  81422. vertexData.merge(primitive.vertexData);
  81423. }
  81424. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  81425. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  81426. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  81427. node.babylonMesh.subMeshes = [];
  81428. var verticesStart = 0;
  81429. var indicesStart = 0;
  81430. for (var index = 0; index < primitives.length; index++) {
  81431. var vertexData_1 = primitives[index].vertexData;
  81432. var verticesCount = vertexData_1.positions.length;
  81433. var indicesCount = vertexData_1.indices.length;
  81434. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  81435. verticesStart += verticesCount;
  81436. indicesStart += indicesCount;
  81437. }
  81438. ;
  81439. });
  81440. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  81441. node.babylonMesh.material = multiMaterial;
  81442. var subMaterials = multiMaterial.subMaterials;
  81443. var _loop_1 = function (index) {
  81444. var primitive = primitives[index];
  81445. if (primitive.material == null) {
  81446. subMaterials[index] = this_1._getDefaultMaterial();
  81447. }
  81448. else {
  81449. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  81450. if (!material) {
  81451. throw new Error(context + ": Failed to find material " + primitive.material);
  81452. }
  81453. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  81454. if (isNew && _this._parent.onMaterialLoaded) {
  81455. _this._parent.onMaterialLoaded(babylonMaterial);
  81456. }
  81457. subMaterials[index] = babylonMaterial;
  81458. });
  81459. }
  81460. };
  81461. var this_1 = this;
  81462. for (var index = 0; index < primitives.length; index++) {
  81463. _loop_1(index);
  81464. }
  81465. ;
  81466. };
  81467. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  81468. var primitives = mesh.primitives;
  81469. var numRemainingPrimitives = primitives.length;
  81470. var _loop_2 = function (index) {
  81471. var primitive = primitives[index];
  81472. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  81473. primitive.vertexData = vertexData;
  81474. if (--numRemainingPrimitives === 0) {
  81475. onSuccess();
  81476. }
  81477. });
  81478. };
  81479. var this_2 = this;
  81480. for (var index = 0; index < primitives.length; index++) {
  81481. _loop_2(index);
  81482. }
  81483. };
  81484. /**
  81485. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  81486. * @param {ArrayBufferView} data
  81487. * @param {IGLTFAccessor} accessor
  81488. */
  81489. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  81490. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  81491. return data;
  81492. }
  81493. var buffer = data;
  81494. var factor = 1;
  81495. switch (accessor.componentType) {
  81496. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81497. factor = 1 / 255;
  81498. break;
  81499. }
  81500. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81501. factor = 1 / 65535;
  81502. break;
  81503. }
  81504. default: {
  81505. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81506. }
  81507. }
  81508. var result = new Float32Array(accessor.count * 2);
  81509. for (var i = 0; i < result.length; ++i) {
  81510. result[i] = buffer[i] * factor;
  81511. }
  81512. return result;
  81513. };
  81514. /**
  81515. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  81516. * @param {ArrayBufferView} data
  81517. * @param {IGLTFAccessor} accessor
  81518. */
  81519. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  81520. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  81521. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  81522. return data;
  81523. }
  81524. var buffer = data;
  81525. var factor = 1;
  81526. switch (accessor.componentType) {
  81527. case GLTF2.EComponentType.FLOAT: {
  81528. factor = 1;
  81529. break;
  81530. }
  81531. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81532. factor = 1 / 255;
  81533. break;
  81534. }
  81535. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81536. factor = 1 / 65535;
  81537. break;
  81538. }
  81539. default: {
  81540. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81541. }
  81542. }
  81543. var result = new Float32Array(accessor.count * 4);
  81544. if (colorComponentCount === 4) {
  81545. for (var i = 0; i < result.length; ++i) {
  81546. result[i] = buffer[i] * factor;
  81547. }
  81548. }
  81549. else {
  81550. var offset = 0;
  81551. for (var i = 0; i < result.length; ++i) {
  81552. if ((i + 1) % 4 === 0) {
  81553. result[i] = 1;
  81554. }
  81555. else {
  81556. result[i] = buffer[offset++] * factor;
  81557. }
  81558. }
  81559. }
  81560. return result;
  81561. };
  81562. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  81563. var _this = this;
  81564. var attributes = primitive.attributes;
  81565. if (!attributes) {
  81566. throw new Error(context + ": Attributes are missing");
  81567. }
  81568. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  81569. // TODO: handle other primitive modes
  81570. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  81571. }
  81572. var vertexData = new BABYLON.VertexData();
  81573. var numRemainingAttributes = Object.keys(attributes).length;
  81574. var _loop_3 = function (attribute) {
  81575. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  81576. if (!accessor) {
  81577. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  81578. }
  81579. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81580. switch (attribute) {
  81581. case "POSITION": {
  81582. vertexData.positions = data;
  81583. break;
  81584. }
  81585. case "NORMAL": {
  81586. vertexData.normals = data;
  81587. break;
  81588. }
  81589. case "TANGENT": {
  81590. vertexData.tangents = data;
  81591. break;
  81592. }
  81593. case "TEXCOORD_0": {
  81594. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81595. break;
  81596. }
  81597. case "TEXCOORD_1": {
  81598. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81599. break;
  81600. }
  81601. case "JOINTS_0": {
  81602. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  81603. break;
  81604. }
  81605. case "WEIGHTS_0": {
  81606. //TODO: need to add support for normalized weights.
  81607. vertexData.matricesWeights = data;
  81608. break;
  81609. }
  81610. case "COLOR_0": {
  81611. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  81612. break;
  81613. }
  81614. default: {
  81615. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  81616. break;
  81617. }
  81618. }
  81619. if (--numRemainingAttributes === 0) {
  81620. if (primitive.indices == null) {
  81621. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  81622. for (var i = 0; i < vertexData.indices.length; i++) {
  81623. vertexData.indices[i] = i;
  81624. }
  81625. onSuccess(vertexData);
  81626. }
  81627. else {
  81628. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  81629. if (!indicesAccessor) {
  81630. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  81631. }
  81632. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  81633. vertexData.indices = data;
  81634. onSuccess(vertexData);
  81635. });
  81636. }
  81637. }
  81638. });
  81639. };
  81640. var this_3 = this;
  81641. for (var attribute in attributes) {
  81642. _loop_3(attribute);
  81643. }
  81644. };
  81645. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  81646. var primitives = mesh.primitives;
  81647. var targets = primitives[0].targets;
  81648. if (!targets) {
  81649. return;
  81650. }
  81651. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  81652. var primitive = primitives_2[_i];
  81653. if (!primitive.targets || primitive.targets.length != targets.length) {
  81654. throw new Error(context + ": All primitives are required to list the same number of targets");
  81655. }
  81656. }
  81657. var morphTargetManager = new BABYLON.MorphTargetManager();
  81658. node.babylonMesh.morphTargetManager = morphTargetManager;
  81659. for (var index = 0; index < targets.length; index++) {
  81660. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  81661. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  81662. }
  81663. };
  81664. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  81665. var morphTargetManager = node.babylonMesh.morphTargetManager;
  81666. if (!morphTargetManager) {
  81667. return;
  81668. }
  81669. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  81670. var numTargets = morphTargetManager.numTargets;
  81671. for (var index = 0; index < numTargets; index++) {
  81672. var vertexData = new BABYLON.VertexData();
  81673. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  81674. var primitive = _a[_i];
  81675. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  81676. }
  81677. if (!vertexData.positions) {
  81678. throw new Error(context + ": Positions are missing");
  81679. }
  81680. var target = morphTargetManager.getTarget(index);
  81681. target.setPositions(vertexData.positions);
  81682. target.setNormals(vertexData.normals);
  81683. target.setTangents(vertexData.tangents);
  81684. }
  81685. });
  81686. };
  81687. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  81688. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  81689. var _loop_4 = function (primitive) {
  81690. var targets = primitive.targets;
  81691. primitive.targetsVertexData = new Array(targets.length);
  81692. var _loop_5 = function (index) {
  81693. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  81694. primitive.targetsVertexData[index] = vertexData;
  81695. if (--numRemainingTargets === 0) {
  81696. onSuccess();
  81697. }
  81698. });
  81699. };
  81700. for (var index = 0; index < targets.length; index++) {
  81701. _loop_5(index);
  81702. }
  81703. };
  81704. var this_4 = this;
  81705. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  81706. var primitive = _a[_i];
  81707. _loop_4(primitive);
  81708. }
  81709. };
  81710. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  81711. var targetVertexData = new BABYLON.VertexData();
  81712. var numRemainingAttributes = Object.keys(attributes).length;
  81713. var _loop_6 = function (attribute) {
  81714. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  81715. if (!accessor) {
  81716. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  81717. }
  81718. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81719. // glTF stores morph target information as deltas while babylon.js expects the final data.
  81720. // As a result we have to add the original data to the delta to calculate the final data.
  81721. var values = data;
  81722. switch (attribute) {
  81723. case "POSITION": {
  81724. for (var i = 0; i < values.length; i++) {
  81725. values[i] += vertexData.positions[i];
  81726. }
  81727. targetVertexData.positions = values;
  81728. break;
  81729. }
  81730. case "NORMAL": {
  81731. for (var i = 0; i < values.length; i++) {
  81732. values[i] += vertexData.normals[i];
  81733. }
  81734. targetVertexData.normals = values;
  81735. break;
  81736. }
  81737. case "TANGENT": {
  81738. // Tangent data for morph targets is stored as xyz delta.
  81739. // The vertexData.tangent is stored as xyzw.
  81740. // So we need to skip every fourth vertexData.tangent.
  81741. for (var i = 0, j = 0; i < values.length; i++, j++) {
  81742. values[i] += vertexData.tangents[j];
  81743. if ((i + 1) % 3 == 0) {
  81744. j++;
  81745. }
  81746. }
  81747. targetVertexData.tangents = values;
  81748. break;
  81749. }
  81750. default: {
  81751. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  81752. break;
  81753. }
  81754. }
  81755. if (--numRemainingAttributes === 0) {
  81756. onSuccess(targetVertexData);
  81757. }
  81758. });
  81759. };
  81760. var this_5 = this;
  81761. for (var attribute in attributes) {
  81762. _loop_6(attribute);
  81763. }
  81764. };
  81765. GLTFLoader.prototype._loadTransform = function (node) {
  81766. var position = BABYLON.Vector3.Zero();
  81767. var rotation = BABYLON.Quaternion.Identity();
  81768. var scaling = BABYLON.Vector3.One();
  81769. if (node.matrix) {
  81770. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  81771. matrix.decompose(scaling, rotation, position);
  81772. }
  81773. else {
  81774. if (node.translation)
  81775. position = BABYLON.Vector3.FromArray(node.translation);
  81776. if (node.rotation)
  81777. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  81778. if (node.scale)
  81779. scaling = BABYLON.Vector3.FromArray(node.scale);
  81780. }
  81781. node.babylonMesh.position = position;
  81782. node.babylonMesh.rotationQuaternion = rotation;
  81783. node.babylonMesh.scaling = scaling;
  81784. };
  81785. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  81786. var _this = this;
  81787. if (skin.babylonSkeleton) {
  81788. onSuccess();
  81789. return;
  81790. }
  81791. var skeletonId = "skeleton" + skin.index;
  81792. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  81793. if (skin.inverseBindMatrices == null) {
  81794. this._loadBones(context, skin, null);
  81795. onSuccess();
  81796. }
  81797. else {
  81798. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  81799. if (!accessor) {
  81800. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  81801. }
  81802. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81803. _this._loadBones(context, skin, data);
  81804. onSuccess();
  81805. });
  81806. }
  81807. };
  81808. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  81809. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  81810. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  81811. node.babylonAnimationTargets.push(babylonBone);
  81812. return babylonBone;
  81813. };
  81814. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  81815. var babylonBones = {};
  81816. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  81817. var index = _a[_i];
  81818. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81819. if (!node) {
  81820. throw new Error(context + ": Failed to find joint " + index);
  81821. }
  81822. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  81823. }
  81824. };
  81825. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  81826. var babylonBone = babylonBones[node.index];
  81827. if (babylonBone) {
  81828. return babylonBone;
  81829. }
  81830. var boneIndex = skin.joints.indexOf(node.index);
  81831. var baseMatrix = BABYLON.Matrix.Identity();
  81832. if (inverseBindMatrixData && boneIndex !== -1) {
  81833. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  81834. baseMatrix.invertToRef(baseMatrix);
  81835. }
  81836. var babylonParentBone = null;
  81837. if (node.parent !== this._rootNode) {
  81838. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  81839. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  81840. }
  81841. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  81842. babylonBones[node.index] = babylonBone;
  81843. return babylonBone;
  81844. };
  81845. GLTFLoader.prototype._getNodeMatrix = function (node) {
  81846. return node.matrix ?
  81847. BABYLON.Matrix.FromArray(node.matrix) :
  81848. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  81849. };
  81850. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  81851. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  81852. var index = indices_1[_i];
  81853. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81854. if (!node) {
  81855. throw new Error(context + ": Failed to find node " + index);
  81856. }
  81857. this._traverseNode(context, node, action, parentNode);
  81858. }
  81859. };
  81860. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  81861. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  81862. return;
  81863. }
  81864. if (!action(node, parentNode)) {
  81865. return;
  81866. }
  81867. if (node.children) {
  81868. this._traverseNodes(context, node.children, action, node);
  81869. }
  81870. };
  81871. GLTFLoader.prototype._loadAnimations = function () {
  81872. var animations = this._gltf.animations;
  81873. if (!animations) {
  81874. return;
  81875. }
  81876. for (var index = 0; index < animations.length; index++) {
  81877. var animation = animations[index];
  81878. this._loadAnimation("#/animations/" + index, animation);
  81879. }
  81880. };
  81881. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  81882. animation.targets = [];
  81883. for (var index = 0; index < animation.channels.length; index++) {
  81884. var channel = GLTFLoader._GetProperty(animation.channels, index);
  81885. if (!channel) {
  81886. throw new Error(context + ": Failed to find channel " + index);
  81887. }
  81888. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  81889. if (!sampler) {
  81890. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  81891. }
  81892. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  81893. }
  81894. };
  81895. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  81896. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  81897. if (!targetNode) {
  81898. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  81899. }
  81900. var targetPath;
  81901. var animationType;
  81902. switch (channel.target.path) {
  81903. case "translation": {
  81904. targetPath = "position";
  81905. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  81906. break;
  81907. }
  81908. case "rotation": {
  81909. targetPath = "rotationQuaternion";
  81910. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  81911. break;
  81912. }
  81913. case "scale": {
  81914. targetPath = "scaling";
  81915. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  81916. break;
  81917. }
  81918. case "weights": {
  81919. targetPath = "influence";
  81920. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  81921. break;
  81922. }
  81923. default: {
  81924. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  81925. }
  81926. }
  81927. var inputData;
  81928. var outputData;
  81929. var checkSuccess = function () {
  81930. if (!inputData || !outputData) {
  81931. return;
  81932. }
  81933. var outputBufferOffset = 0;
  81934. var getNextOutputValue;
  81935. switch (targetPath) {
  81936. case "position": {
  81937. getNextOutputValue = function () {
  81938. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81939. outputBufferOffset += 3;
  81940. return value;
  81941. };
  81942. break;
  81943. }
  81944. case "rotationQuaternion": {
  81945. getNextOutputValue = function () {
  81946. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  81947. outputBufferOffset += 4;
  81948. return value;
  81949. };
  81950. break;
  81951. }
  81952. case "scaling": {
  81953. getNextOutputValue = function () {
  81954. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81955. outputBufferOffset += 3;
  81956. return value;
  81957. };
  81958. break;
  81959. }
  81960. case "influence": {
  81961. getNextOutputValue = function () {
  81962. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  81963. var value = new Array(numTargets);
  81964. for (var i = 0; i < numTargets; i++) {
  81965. value[i] = outputData[outputBufferOffset++];
  81966. }
  81967. return value;
  81968. };
  81969. break;
  81970. }
  81971. }
  81972. var getNextKey;
  81973. switch (sampler.interpolation) {
  81974. case "LINEAR": {
  81975. getNextKey = function (frameIndex) { return ({
  81976. frame: inputData[frameIndex],
  81977. value: getNextOutputValue()
  81978. }); };
  81979. break;
  81980. }
  81981. case "CUBICSPLINE": {
  81982. getNextKey = function (frameIndex) { return ({
  81983. frame: inputData[frameIndex],
  81984. inTangent: getNextOutputValue(),
  81985. value: getNextOutputValue(),
  81986. outTangent: getNextOutputValue()
  81987. }); };
  81988. break;
  81989. }
  81990. default: {
  81991. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  81992. }
  81993. }
  81994. ;
  81995. var keys;
  81996. if (inputData.length === 1) {
  81997. var key = getNextKey(0);
  81998. keys = [
  81999. { frame: key.frame, value: key.value },
  82000. { frame: key.frame + 1, value: key.value }
  82001. ];
  82002. }
  82003. else {
  82004. keys = new Array(inputData.length);
  82005. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  82006. keys[frameIndex] = getNextKey(frameIndex);
  82007. }
  82008. }
  82009. if (targetPath === "influence") {
  82010. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  82011. var _loop_7 = function (targetIndex) {
  82012. var morphTarget = morphTargetManager.getTarget(targetIndex);
  82013. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  82014. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82015. babylonAnimation.setKeys(keys.map(function (key) { return ({
  82016. frame: key.frame,
  82017. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  82018. value: key.value[targetIndex],
  82019. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  82020. }); }));
  82021. morphTarget.animations.push(babylonAnimation);
  82022. animation.targets.push(morphTarget);
  82023. };
  82024. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  82025. _loop_7(targetIndex);
  82026. }
  82027. }
  82028. else {
  82029. var animationName = animation.name || "anim" + animation.index;
  82030. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82031. babylonAnimation.setKeys(keys);
  82032. if (targetNode.babylonAnimationTargets) {
  82033. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  82034. var target = _a[_i];
  82035. target.animations.push(babylonAnimation.clone());
  82036. animation.targets.push(target);
  82037. }
  82038. }
  82039. }
  82040. };
  82041. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  82042. if (!inputAccessor) {
  82043. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  82044. }
  82045. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  82046. inputData = data;
  82047. checkSuccess();
  82048. });
  82049. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  82050. if (!outputAccessor) {
  82051. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  82052. }
  82053. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  82054. outputData = data;
  82055. checkSuccess();
  82056. });
  82057. };
  82058. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  82059. var _this = this;
  82060. this._addPendingData(buffer);
  82061. if (buffer.loadedData) {
  82062. onSuccess(buffer.loadedData);
  82063. this._removePendingData(buffer);
  82064. }
  82065. else if (buffer.loadedObservable) {
  82066. buffer.loadedObservable.add(function (buffer) {
  82067. onSuccess(buffer.loadedData);
  82068. _this._removePendingData(buffer);
  82069. });
  82070. }
  82071. else {
  82072. if (!buffer.uri) {
  82073. throw new Error(context + ": Uri is missing");
  82074. }
  82075. buffer.loadedObservable = new BABYLON.Observable();
  82076. buffer.loadedObservable.add(function (buffer) {
  82077. onSuccess(buffer.loadedData);
  82078. _this._removePendingData(buffer);
  82079. });
  82080. this._loadUriAsync(context, buffer.uri, function (data) {
  82081. buffer.loadedData = data;
  82082. buffer.loadedObservable.notifyObservers(buffer);
  82083. buffer.loadedObservable = undefined;
  82084. });
  82085. }
  82086. };
  82087. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  82088. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  82089. if (!buffer) {
  82090. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  82091. }
  82092. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  82093. var data;
  82094. try {
  82095. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  82096. }
  82097. catch (e) {
  82098. throw new Error(context + ": " + e.message);
  82099. }
  82100. onSuccess(data);
  82101. });
  82102. };
  82103. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  82104. var _this = this;
  82105. if (accessor.sparse) {
  82106. throw new Error(context + ": Sparse accessors are not currently supported");
  82107. }
  82108. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  82109. if (!bufferView) {
  82110. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  82111. }
  82112. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  82113. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  82114. if (numComponents === 0) {
  82115. throw new Error(context + ": Invalid type " + accessor.type);
  82116. }
  82117. var data;
  82118. var byteOffset = accessor.byteOffset || 0;
  82119. var byteStride = bufferView.byteStride;
  82120. try {
  82121. switch (accessor.componentType) {
  82122. case GLTF2.EComponentType.BYTE: {
  82123. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82124. break;
  82125. }
  82126. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82127. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82128. break;
  82129. }
  82130. case GLTF2.EComponentType.SHORT: {
  82131. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82132. break;
  82133. }
  82134. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82135. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82136. break;
  82137. }
  82138. case GLTF2.EComponentType.UNSIGNED_INT: {
  82139. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82140. break;
  82141. }
  82142. case GLTF2.EComponentType.FLOAT: {
  82143. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82144. break;
  82145. }
  82146. default: {
  82147. throw new Error(context + ": Invalid component type " + accessor.componentType);
  82148. }
  82149. }
  82150. }
  82151. catch (e) {
  82152. throw new Error(context + ": " + e);
  82153. }
  82154. onSuccess(data);
  82155. });
  82156. };
  82157. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  82158. byteOffset += data.byteOffset;
  82159. var targetLength = count * numComponents;
  82160. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  82161. return new typedArray(data.buffer, byteOffset, targetLength);
  82162. }
  82163. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  82164. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  82165. var targetBuffer = new typedArray(targetLength);
  82166. var sourceIndex = 0;
  82167. var targetIndex = 0;
  82168. while (targetIndex < targetLength) {
  82169. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  82170. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  82171. targetIndex++;
  82172. }
  82173. sourceIndex += elementStride;
  82174. }
  82175. return targetBuffer;
  82176. };
  82177. GLTFLoader.prototype._addPendingData = function (data) {
  82178. if (!this._renderReady) {
  82179. this._renderPendingCount++;
  82180. }
  82181. this._addLoaderPendingData(data);
  82182. };
  82183. GLTFLoader.prototype._removePendingData = function (data) {
  82184. var _this = this;
  82185. if (!this._renderReady) {
  82186. if (--this._renderPendingCount === 0) {
  82187. this._addLoaderPendingData(this);
  82188. this._compileMaterialsAsync(function () {
  82189. _this._compileShadowGeneratorsAsync(function () {
  82190. _this._removeLoaderPendingData(_this);
  82191. _this._renderReady = true;
  82192. _this._onRenderReady();
  82193. });
  82194. });
  82195. }
  82196. }
  82197. this._removeLoaderPendingData(data);
  82198. };
  82199. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  82200. this._loaderPendingCount++;
  82201. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  82202. var tracker = _a[_i];
  82203. tracker._addPendingData(data);
  82204. }
  82205. };
  82206. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  82207. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  82208. var tracker = _a[_i];
  82209. tracker._removePendingData(data);
  82210. }
  82211. if (--this._loaderPendingCount === 0) {
  82212. this._onComplete();
  82213. }
  82214. };
  82215. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  82216. var _this = this;
  82217. var tracker = new GLTFLoaderTracker(function () {
  82218. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  82219. onComplete();
  82220. });
  82221. this._loaderTrackers.push(tracker);
  82222. this._addLoaderPendingData(tracker);
  82223. action();
  82224. this._removeLoaderPendingData(tracker);
  82225. };
  82226. GLTFLoader.prototype._getDefaultMaterial = function () {
  82227. if (!this._defaultMaterial) {
  82228. var id = "__gltf_default";
  82229. var material = this._babylonScene.getMaterialByName(id);
  82230. if (!material) {
  82231. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  82232. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82233. material.metallic = 1;
  82234. material.roughness = 1;
  82235. }
  82236. this._defaultMaterial = material;
  82237. }
  82238. return this._defaultMaterial;
  82239. };
  82240. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  82241. var babylonMaterial = material.babylonMaterial;
  82242. // Ensure metallic workflow
  82243. babylonMaterial.metallic = 1;
  82244. babylonMaterial.roughness = 1;
  82245. var properties = material.pbrMetallicRoughness;
  82246. if (!properties) {
  82247. return;
  82248. }
  82249. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  82250. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  82251. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  82252. if (properties.baseColorTexture) {
  82253. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  82254. if (!texture) {
  82255. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  82256. }
  82257. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  82258. }
  82259. if (properties.metallicRoughnessTexture) {
  82260. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  82261. if (!texture) {
  82262. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  82263. }
  82264. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  82265. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  82266. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  82267. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  82268. }
  82269. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  82270. };
  82271. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  82272. if (material.babylonMaterial) {
  82273. assign(material.babylonMaterial, false);
  82274. return;
  82275. }
  82276. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  82277. return;
  82278. }
  82279. this._createPbrMaterial(material);
  82280. this._loadMaterialBaseProperties(context, material);
  82281. this._loadMaterialMetallicRoughnessProperties(context, material);
  82282. assign(material.babylonMaterial, true);
  82283. };
  82284. GLTFLoader.prototype._createPbrMaterial = function (material) {
  82285. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  82286. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82287. material.babylonMaterial = babylonMaterial;
  82288. };
  82289. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  82290. var babylonMaterial = material.babylonMaterial;
  82291. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  82292. if (material.doubleSided) {
  82293. babylonMaterial.backFaceCulling = false;
  82294. babylonMaterial.twoSidedLighting = true;
  82295. }
  82296. if (material.normalTexture) {
  82297. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  82298. if (!texture) {
  82299. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  82300. }
  82301. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  82302. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  82303. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  82304. if (material.normalTexture.scale != null) {
  82305. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  82306. }
  82307. }
  82308. if (material.occlusionTexture) {
  82309. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  82310. if (!texture) {
  82311. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  82312. }
  82313. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  82314. babylonMaterial.useAmbientInGrayScale = true;
  82315. if (material.occlusionTexture.strength != null) {
  82316. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  82317. }
  82318. }
  82319. if (material.emissiveTexture) {
  82320. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  82321. if (!texture) {
  82322. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  82323. }
  82324. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  82325. }
  82326. };
  82327. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  82328. var babylonMaterial = material.babylonMaterial;
  82329. var alphaMode = material.alphaMode || "OPAQUE";
  82330. switch (alphaMode) {
  82331. case "OPAQUE": {
  82332. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  82333. break;
  82334. }
  82335. case "MASK": {
  82336. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  82337. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  82338. if (colorFactor) {
  82339. if (colorFactor[3] == 0) {
  82340. babylonMaterial.alphaCutOff = 1;
  82341. }
  82342. else {
  82343. babylonMaterial.alphaCutOff /= colorFactor[3];
  82344. }
  82345. }
  82346. if (babylonMaterial.albedoTexture) {
  82347. babylonMaterial.albedoTexture.hasAlpha = true;
  82348. }
  82349. break;
  82350. }
  82351. case "BLEND": {
  82352. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  82353. if (colorFactor) {
  82354. babylonMaterial.alpha = colorFactor[3];
  82355. }
  82356. if (babylonMaterial.albedoTexture) {
  82357. babylonMaterial.albedoTexture.hasAlpha = true;
  82358. babylonMaterial.useAlphaFromAlbedoTexture = true;
  82359. }
  82360. break;
  82361. }
  82362. default: {
  82363. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  82364. }
  82365. }
  82366. };
  82367. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  82368. var _this = this;
  82369. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  82370. if (!sampler) {
  82371. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  82372. }
  82373. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  82374. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  82375. this._addPendingData(texture);
  82376. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  82377. _this._tryCatchOnError(function () {
  82378. _this._removePendingData(texture);
  82379. });
  82380. }, function (message) {
  82381. _this._tryCatchOnError(function () {
  82382. throw new Error(context + ": " + message);
  82383. });
  82384. });
  82385. if (texture.url) {
  82386. babylonTexture.updateURL(texture.url);
  82387. }
  82388. else if (texture.dataReadyObservable) {
  82389. texture.dataReadyObservable.add(function (texture) {
  82390. babylonTexture.updateURL(texture.url);
  82391. });
  82392. }
  82393. else {
  82394. texture.dataReadyObservable = new BABYLON.Observable();
  82395. texture.dataReadyObservable.add(function (texture) {
  82396. babylonTexture.updateURL(texture.url);
  82397. });
  82398. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  82399. if (!image_1) {
  82400. throw new Error(context + ": Failed to find source " + texture.source);
  82401. }
  82402. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  82403. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  82404. texture.dataReadyObservable.notifyObservers(texture);
  82405. texture.dataReadyObservable = undefined;
  82406. });
  82407. }
  82408. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  82409. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  82410. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  82411. babylonTexture.name = texture.name || "texture" + texture.index;
  82412. if (this._parent.onTextureLoaded) {
  82413. this._parent.onTextureLoaded(babylonTexture);
  82414. }
  82415. return babylonTexture;
  82416. };
  82417. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  82418. if (image.uri) {
  82419. this._loadUriAsync(context, image.uri, onSuccess);
  82420. }
  82421. else {
  82422. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  82423. if (!bufferView) {
  82424. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  82425. }
  82426. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  82427. }
  82428. };
  82429. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  82430. var _this = this;
  82431. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  82432. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  82433. return;
  82434. }
  82435. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  82436. throw new Error(context + ": Uri '" + uri + "' is invalid");
  82437. }
  82438. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  82439. _this._tryCatchOnError(function () {
  82440. onSuccess(new Uint8Array(data));
  82441. });
  82442. }, function (event) {
  82443. _this._tryCatchOnError(function () {
  82444. if (request && !_this._renderReady) {
  82445. request._loaded = event.loaded;
  82446. request._total = event.total;
  82447. _this._onProgress();
  82448. }
  82449. });
  82450. }, this._babylonScene.database, true, function (request) {
  82451. _this._tryCatchOnError(function () {
  82452. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  82453. });
  82454. });
  82455. if (request) {
  82456. request._loaded = null;
  82457. request._total = null;
  82458. this._requests.push(request);
  82459. }
  82460. };
  82461. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  82462. if (this._disposed) {
  82463. return;
  82464. }
  82465. try {
  82466. handler();
  82467. }
  82468. catch (e) {
  82469. BABYLON.Tools.Error("glTF Loader: " + e.message);
  82470. if (this._errorCallback) {
  82471. this._errorCallback(e.message);
  82472. }
  82473. this.dispose();
  82474. }
  82475. };
  82476. GLTFLoader._AssignIndices = function (array) {
  82477. if (array) {
  82478. for (var index = 0; index < array.length; index++) {
  82479. array[index].index = index;
  82480. }
  82481. }
  82482. };
  82483. GLTFLoader._GetProperty = function (array, index) {
  82484. if (!array || index == undefined || !array[index]) {
  82485. return null;
  82486. }
  82487. return array[index];
  82488. };
  82489. GLTFLoader._GetTextureWrapMode = function (mode) {
  82490. // Set defaults if undefined
  82491. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  82492. switch (mode) {
  82493. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  82494. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  82495. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  82496. default:
  82497. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  82498. return BABYLON.Texture.WRAP_ADDRESSMODE;
  82499. }
  82500. };
  82501. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  82502. // Set defaults if undefined
  82503. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  82504. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  82505. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  82506. switch (minFilter) {
  82507. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  82508. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  82509. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  82510. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  82511. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  82512. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82513. default:
  82514. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82515. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82516. }
  82517. }
  82518. else {
  82519. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  82520. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  82521. }
  82522. switch (minFilter) {
  82523. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  82524. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  82525. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82526. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  82527. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  82528. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  82529. default:
  82530. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82531. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82532. }
  82533. }
  82534. };
  82535. GLTFLoader._GetNumComponents = function (type) {
  82536. switch (type) {
  82537. case "SCALAR": return 1;
  82538. case "VEC2": return 2;
  82539. case "VEC3": return 3;
  82540. case "VEC4": return 4;
  82541. case "MAT2": return 4;
  82542. case "MAT3": return 9;
  82543. case "MAT4": return 16;
  82544. }
  82545. return 0;
  82546. };
  82547. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  82548. var _this = this;
  82549. if (!this._parent.compileMaterials) {
  82550. onSuccess();
  82551. return;
  82552. }
  82553. if (this._parent.useClipPlane) {
  82554. babylonMaterial.forceCompilation(babylonMesh, function () {
  82555. babylonMaterial.forceCompilation(babylonMesh, function () {
  82556. _this._tryCatchOnError(onSuccess);
  82557. }, { clipPlane: true });
  82558. });
  82559. }
  82560. else {
  82561. babylonMaterial.forceCompilation(babylonMesh, function () {
  82562. _this._tryCatchOnError(onSuccess);
  82563. });
  82564. }
  82565. };
  82566. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  82567. if (!this._parent.compileMaterials || !this._gltf.materials) {
  82568. onSuccess();
  82569. return;
  82570. }
  82571. var meshes = this._getMeshes();
  82572. var remaining = 0;
  82573. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  82574. var mesh = meshes_1[_i];
  82575. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82576. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  82577. var subMaterial = _b[_a];
  82578. if (subMaterial) {
  82579. remaining++;
  82580. }
  82581. }
  82582. }
  82583. }
  82584. if (remaining === 0) {
  82585. onSuccess();
  82586. return;
  82587. }
  82588. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  82589. var mesh = meshes_2[_c];
  82590. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82591. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  82592. var subMaterial = _e[_d];
  82593. if (subMaterial) {
  82594. this._compileMaterialAsync(subMaterial, mesh, function () {
  82595. if (--remaining === 0) {
  82596. onSuccess();
  82597. }
  82598. });
  82599. }
  82600. }
  82601. }
  82602. }
  82603. };
  82604. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  82605. var _this = this;
  82606. if (!this._parent.compileShadowGenerators) {
  82607. onSuccess();
  82608. return;
  82609. }
  82610. var lights = this._babylonScene.lights;
  82611. var remaining = 0;
  82612. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  82613. var light = lights_1[_i];
  82614. var generator = light.getShadowGenerator();
  82615. if (generator) {
  82616. remaining++;
  82617. }
  82618. }
  82619. if (remaining === 0) {
  82620. onSuccess();
  82621. return;
  82622. }
  82623. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  82624. var light = lights_2[_a];
  82625. var generator = light.getShadowGenerator();
  82626. if (generator) {
  82627. generator.forceCompilation(function () {
  82628. if (--remaining === 0) {
  82629. _this._tryCatchOnError(onSuccess);
  82630. }
  82631. });
  82632. }
  82633. }
  82634. };
  82635. GLTFLoader.Extensions = {};
  82636. return GLTFLoader;
  82637. }());
  82638. GLTF2.GLTFLoader = GLTFLoader;
  82639. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  82640. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82641. })(BABYLON || (BABYLON = {}));
  82642. //# sourceMappingURL=babylon.glTFLoader.js.map
  82643. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82644. var BABYLON;
  82645. (function (BABYLON) {
  82646. var GLTF2;
  82647. (function (GLTF2) {
  82648. /**
  82649. * Utils functions for GLTF
  82650. */
  82651. var GLTFUtils = /** @class */ (function () {
  82652. function GLTFUtils() {
  82653. }
  82654. /**
  82655. * If the uri is a base64 string
  82656. * @param uri: the uri to test
  82657. */
  82658. GLTFUtils.IsBase64 = function (uri) {
  82659. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  82660. };
  82661. /**
  82662. * Decode the base64 uri
  82663. * @param uri: the uri to decode
  82664. */
  82665. GLTFUtils.DecodeBase64 = function (uri) {
  82666. var decodedString = atob(uri.split(",")[1]);
  82667. var bufferLength = decodedString.length;
  82668. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  82669. for (var i = 0; i < bufferLength; i++) {
  82670. bufferView[i] = decodedString.charCodeAt(i);
  82671. }
  82672. return bufferView.buffer;
  82673. };
  82674. GLTFUtils.ValidateUri = function (uri) {
  82675. return (uri.indexOf("..") === -1);
  82676. };
  82677. return GLTFUtils;
  82678. }());
  82679. GLTF2.GLTFUtils = GLTFUtils;
  82680. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82681. })(BABYLON || (BABYLON = {}));
  82682. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  82683. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82684. var BABYLON;
  82685. (function (BABYLON) {
  82686. var GLTF2;
  82687. (function (GLTF2) {
  82688. var GLTFLoaderExtension = /** @class */ (function () {
  82689. function GLTFLoaderExtension() {
  82690. this.enabled = true;
  82691. }
  82692. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  82693. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  82694. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  82695. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  82696. var _this = this;
  82697. if (!property.extensions) {
  82698. return false;
  82699. }
  82700. var extension = property.extensions[this.name];
  82701. if (!extension) {
  82702. return false;
  82703. }
  82704. // Clear out the extension before executing the action to avoid recursing into the same property.
  82705. property.extensions[this.name] = undefined;
  82706. action(context + "extensions/" + this.name, extension, function () {
  82707. // Restore the extension after completing the action.
  82708. property.extensions[_this.name] = extension;
  82709. });
  82710. return true;
  82711. };
  82712. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  82713. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  82714. };
  82715. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  82716. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  82717. };
  82718. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  82719. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  82720. };
  82721. GLTFLoaderExtension._ApplyExtensions = function (action) {
  82722. var extensions = GLTFLoaderExtension._Extensions;
  82723. if (!extensions) {
  82724. return false;
  82725. }
  82726. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  82727. var extension = extensions_1[_i];
  82728. if (extension.enabled && action(extension)) {
  82729. return true;
  82730. }
  82731. }
  82732. return false;
  82733. };
  82734. //
  82735. // Utilities
  82736. //
  82737. GLTFLoaderExtension._Extensions = [];
  82738. return GLTFLoaderExtension;
  82739. }());
  82740. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  82741. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82742. })(BABYLON || (BABYLON = {}));
  82743. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  82744. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  82745. var BABYLON;
  82746. (function (BABYLON) {
  82747. var GLTF2;
  82748. (function (GLTF2) {
  82749. var Extensions;
  82750. (function (Extensions) {
  82751. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  82752. var MSFTLOD = /** @class */ (function (_super) {
  82753. __extends(MSFTLOD, _super);
  82754. function MSFTLOD() {
  82755. var _this = _super !== null && _super.apply(this, arguments) || this;
  82756. /**
  82757. * Specify the minimal delay between LODs in ms (default = 250)
  82758. */
  82759. _this.Delay = 250;
  82760. return _this;
  82761. }
  82762. Object.defineProperty(MSFTLOD.prototype, "name", {
  82763. get: function () {
  82764. return "MSFT_lod";
  82765. },
  82766. enumerable: true,
  82767. configurable: true
  82768. });
  82769. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  82770. return this._loadExtension(context, node, function (context, extension, onComplete) {
  82771. for (var i = extension.ids.length - 1; i >= 0; i--) {
  82772. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  82773. if (!lodNode) {
  82774. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  82775. }
  82776. loader._traverseNode(context, lodNode, action, parentNode);
  82777. }
  82778. loader._traverseNode(context, node, action, parentNode);
  82779. onComplete();
  82780. });
  82781. };
  82782. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  82783. var _this = this;
  82784. return this._loadExtension(context, node, function (context, extension, onComplete) {
  82785. var nodes = [node];
  82786. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  82787. var index = _a[_i];
  82788. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  82789. if (!lodNode) {
  82790. throw new Error(context + ": Failed to find node " + index);
  82791. }
  82792. nodes.push(lodNode);
  82793. }
  82794. loader._addLoaderPendingData(node);
  82795. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  82796. loader._removeLoaderPendingData(node);
  82797. onComplete();
  82798. });
  82799. });
  82800. };
  82801. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  82802. var _this = this;
  82803. loader._whenAction(function () {
  82804. loader._loadNode(context, nodes[index]);
  82805. }, function () {
  82806. if (index !== nodes.length - 1) {
  82807. var previousNode = nodes[index + 1];
  82808. previousNode.babylonMesh.setEnabled(false);
  82809. }
  82810. if (index === 0) {
  82811. onComplete();
  82812. return;
  82813. }
  82814. setTimeout(function () {
  82815. loader._tryCatchOnError(function () {
  82816. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  82817. });
  82818. }, _this.Delay);
  82819. });
  82820. };
  82821. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  82822. var _this = this;
  82823. return this._loadExtension(context, material, function (context, extension, onComplete) {
  82824. var materials = [material];
  82825. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  82826. var index = _a[_i];
  82827. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  82828. if (!lodMaterial) {
  82829. throw new Error(context + ": Failed to find material " + index);
  82830. }
  82831. materials.push(lodMaterial);
  82832. }
  82833. loader._addLoaderPendingData(material);
  82834. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  82835. loader._removeLoaderPendingData(material);
  82836. onComplete();
  82837. });
  82838. });
  82839. };
  82840. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  82841. var _this = this;
  82842. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  82843. if (index === materials.length - 1) {
  82844. assign(babylonMaterial, isNew);
  82845. // Load the next LOD when the loader is ready to render.
  82846. loader._executeWhenRenderReady(function () {
  82847. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  82848. });
  82849. }
  82850. else {
  82851. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  82852. assign(babylonMaterial, isNew);
  82853. if (index === 0) {
  82854. onComplete();
  82855. }
  82856. else {
  82857. setTimeout(function () {
  82858. loader._tryCatchOnError(function () {
  82859. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  82860. });
  82861. }, _this.Delay);
  82862. }
  82863. });
  82864. }
  82865. });
  82866. };
  82867. return MSFTLOD;
  82868. }(GLTF2.GLTFLoaderExtension));
  82869. Extensions.MSFTLOD = MSFTLOD;
  82870. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  82871. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  82872. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82873. })(BABYLON || (BABYLON = {}));
  82874. //# sourceMappingURL=MSFT_lod.js.map
  82875. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  82876. var BABYLON;
  82877. (function (BABYLON) {
  82878. var GLTF2;
  82879. (function (GLTF2) {
  82880. var Extensions;
  82881. (function (Extensions) {
  82882. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  82883. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  82884. function KHRMaterialsPbrSpecularGlossiness() {
  82885. return _super !== null && _super.apply(this, arguments) || this;
  82886. }
  82887. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  82888. get: function () {
  82889. return "KHR_materials_pbrSpecularGlossiness";
  82890. },
  82891. enumerable: true,
  82892. configurable: true
  82893. });
  82894. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  82895. var _this = this;
  82896. return this._loadExtension(context, material, function (context, extension, onComplete) {
  82897. loader._createPbrMaterial(material);
  82898. loader._loadMaterialBaseProperties(context, material);
  82899. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  82900. assign(material.babylonMaterial, true);
  82901. onComplete();
  82902. });
  82903. };
  82904. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  82905. var babylonMaterial = material.babylonMaterial;
  82906. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  82907. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  82908. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  82909. if (properties.diffuseTexture) {
  82910. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  82911. if (!texture) {
  82912. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  82913. }
  82914. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  82915. }
  82916. if (properties.specularGlossinessTexture) {
  82917. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  82918. if (!texture) {
  82919. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  82920. }
  82921. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  82922. babylonMaterial.reflectivityTexture.hasAlpha = true;
  82923. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  82924. }
  82925. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  82926. };
  82927. return KHRMaterialsPbrSpecularGlossiness;
  82928. }(GLTF2.GLTFLoaderExtension));
  82929. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  82930. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  82931. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  82932. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82933. })(BABYLON || (BABYLON = {}));
  82934. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  82935. (function universalModuleDefinition(root, factory) {
  82936. var f = factory();
  82937. if (root && root["BABYLON"]) {
  82938. return;
  82939. }
  82940. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  82941. globalObject["BABYLON"] = f;
  82942. if(typeof exports === 'object' && typeof module === 'object')
  82943. module.exports = f;
  82944. else if(typeof define === 'function' && define.amd)
  82945. define(["BABYLON"], factory);
  82946. else if(typeof exports === 'object')
  82947. exports["BABYLON"] = f;
  82948. else {
  82949. root["BABYLON"] = f;
  82950. }
  82951. })(this, function() {
  82952. return BABYLON;
  82953. });